Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for specifying property model #72

Merged
merged 4 commits into from
Dec 19, 2017
Merged

Conversation

nonplus
Copy link
Contributor

@nonplus nonplus commented Dec 19, 2017

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"}

@gchauvet gchauvet merged commit 3332d1f into z0mt3c:master Dec 19, 2017
@nonplus nonplus deleted the model branch December 19, 2017 17:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants