koajs/parameter

Validate non-string parameters

Opened this issue · 2 comments

Since Koa's ctx.query object has every query parameter set to a string value, this middleware is throwing an error when I attempt to validate a query parameter that should be an integer. For instance, if my URI has a query parameter like ?limit=5 and then I do ctx.verifyParams({ limit: 'int' }); an error is thrown because ctx.query is { limit: '5' }. Is there a way to tell the middleware to attempt to coerce the query parameter's value to the expected type from a string before the validation occurs or a separate middleware that would perform this?

parameter is a strict validation check module and cannot validate a field if you don't cast it to the correct type

// Example code:
if (ctx.query.hasOwnProperty("limit")) {
    if (ctx.query.limit != undefined) {
        ctx.query.limit = parseInt(ctx.query.limit);
    } else {
        delete ctx.query.limit;
    }
}

Hi all,

Parameter class now has a convert option which is able to cast string into other types.
Maybe we can add an argument to let user decide whether to use it or not.

ref: https://github.com/node-modules/parameter#api