z0mt3c / node-restify-validation

Validation for REST Services built with node-restify in node.js
MIT License
91 stars 49 forks source link

Support for specifying property model #72

Closed nonplus closed 6 years ago

nonplus commented 6 years ago

Except for (JSON) request content, request parameters (query, params, headers) contain string values. So even though in your validation you ensure that they match a number or boolean, the application code still needs to deal with type conversions.

In this PR an optional model property can be specified to transform the request value to a specific type. When validation of a property succeeds and a model is specified, the original request value is replaced with the transformed value.

// Creates an instance of date from a numeric or string value
function DateModel(value) {
    return new Date(Number(value) || value);
}

server.get({url: '/search', validation: {
    queries: {
        text: { isRequired: true },
        from: { model: DateModel },
        to: { model: DateModel },
        summary: { isBoolean, model: Boolean },
        page: { isNumber: true, model: Number }
    }
}, function (req, res, next) {
    console.log("Query:", JSON.stringify(req.query));
    res.send(req.query);
}))

When handling the request GET /search?text=Hello&from=2017-12-1&to=1514678400000&summary=true&page=3, the query property types will be string, number, Date, Date and number, respectively and the following will be logged:

Query: {"text":"Hello","from":"2017-12-01T06:00:00.000Z","to":"2017-12-31T00:00:00.000Z","summary":true,"page":3}

Without specifying the model settings, the query property types would have been strings and the following would have been logged:

Query: {"text":"Hello","from":"2017-12-1","to":"1514678400000","summary":"true","page":"3"}