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:
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 amodel
is specified, the original request value is replaced with the transformed value.When handling the request
GET /search?text=Hello&from=2017-12-1&to=1514678400000&summary=true&page=3
, the query property types will bestring
,number
,Date
,Date
andnumber
, respectively and the following will be logged:Without specifying the
model
settings, the query property types would have been strings and the following would have been logged: