timsolov / rest-query-parser

Query Parser for REST
Apache License 2.0
75 stars 21 forks source link

Readme Example gives me an error #12

Open dikkini opened 1 year ago

dikkini commented 1 year ago

Hello! NIce library, very comprehensive functions. I've tried but i got an error from example in Readme.

q2, _ := rqp.NewParse(r.URL.Query(), rqp.Validations{
        "limit:required": rqp.MinMax(10, 100),  // limit must present in the Query part and must be between 10 and 100 (default: Min(1))
        "sort":           rqp.In("id", "name"), // sort could be or not in the query but if it is present it must be equal to "in" or "name"
        "s":              rqp.In("one", "two"), // filter: s - string and equal
        "id:int":         nil,                  // filter: id is integer without additional validation
        "i:int": func(value interface{}) error { // filter: custom func for validating
            if value.(int) > 1 && value.(int) < 10 {
                return nil
            }
            return errors.New("i: must be greater then 1 and lower then 10")
        },
        "email": nil,
        "name":  nil,
    })

URL looks like: ?sort=+name,-id&limit=10&id=1&i[eq]=5&s[eq]=one&email[like]=*tim*|name[like]=*tim*

Error: s[eq]: filter not found

If i remove s[eq] parameter from url query, then i got an error: sort: validation not found

If i remove sort parameter from url query, then i got an error: id: filter not found

Can you tell what i'm doing wrong?

timsolov commented 1 year ago

Hello @dikkini thanks for greetings.

It's mandatory to provide a validation for each filter you like to use in your query parameters because it's important for security you know.

So for:

Error: s[eq]: filter not found

It's necessary to provide:

"s":              rqp.In("one", "two"), // filter: s - string and equal

For:

sort: validation not found

should be:

"sort":           rqp.In("id", "name"),

and for properly working of:

id: filter not found

add to rqp.Validations parameter:

"id:int":         nil,
timsolov commented 1 year ago

And just look at example in cmd/main.go