ljharb / qs

A querystring parser with nesting support
BSD 3-Clause "New" or "Revised" License
8.47k stars 731 forks source link

Add required key and type checking #482

Closed sakgoyal closed 10 months ago

sakgoyal commented 10 months ago

Is there a way to add an option in the parse function which will make certain query keys required? if the key is not present, return a object with {"error" : "Required key missing"} or something like that? Also, add an option to check types of querys. if the query key is the wrong type, throw a similar error

eg:

options = { 
    allowed : ["username", "password", "id", "tags", "something"],
    comma : true, 
    required : ["username", "password", "id"],
    types : {username : string, password : string, something : boolean},

}
parse("username=foo&password=bar&tags=xx,yy,zz&something=baz&extraParam=true", options)`

would return an error because "something" is not a boolean, id key is missing, "extraParam" present. I really want to avoid a lot of boilerplate code to ensure safety in my API.

sakgoyal commented 10 months ago

I just found the package strict-qs. it seems like it is what I need. But I hope it can still be integrated into this package. I feel it should be very important to have strict types to keep things more safe.

ljharb commented 10 months ago

That seems like the separate job of a validator - iow, first you parse, then you validate. JSON schema would work quite well for this; it could be done in a two-liner if needed (with a separate schema json file)

I don’t see any value in conflating these two separate jobs into the same tool.