jsen
jsen copied to clipboard
Collect data from a source object
Provide a mechanism to collect data from javascript objects based on the source
keyword in the schema.
Use case: collect request data from various request sources (path, query, body, etc.) and build a single JSON object to validate.
This also enables lightweight transformations of JSON data objects.
Sample API:
var validate = jsen({
type: 'object',
properties: {
id: {
type: 'integer',
source: 'params.id'
},
firstName: {
type: 'string',
source: 'body.firstName'
},
lastName: {
type: 'string',
source: 'body.lastName'
}
}
});
app.post('/users', function (req, res, next) {
var data = validate.default(req);
console.log(data);
// { id: 123, firstName: 'John', lastName: 'Doe' }
});
+1
@seeden I'd like to elaborate more on this feature, so feel free to share your thoughts as well. Basically, I'm envisioning some simple data collection mechanism where you can easily get a value from a path in an object. This would be ideal in scenarios like the express req
object that contains request data on different keys (e.g. params
, body
, etc.).
Currently, my idea is to provide a simple path string (dot-delimited or possibly JSON Pointer) to extract a data value from the source object. No fancy stuff like relative paths in inner object graphs or data format transformations.
However, this feature can go a long way in becoming a rich and robust data transformation tool for JSON data. Examples I'm looking at are projects like JsonT and Jolt.
If you can share your particular need or idea for this, we can better shape this feature.
I am not sure if we need to be a complex like jsonT. I can see one improvement. Source can be an array of paths like ['body.firstName', 'query.firstName']