vacekj/express-json-validator-middleware

Schema properties default value

Closed this issue · 1 comments

I was wondering if the library supports JSON Schema default values, and if so how would one use them?

I've tried simply setting defaults in the schema declaration, however after passing the validation middleware and trying to access the properties on the effect ( logic middleware ) the properties still dont exist.

Am I doing something wrong or is it not supported / implemented?

const schema = {
type: 'object',
required: ['foo'],
properties: {
foo: { type: 'string' },
bar: { type: 'string', default: 'Bar' }
}
};
app.post('/foo', validate({body: schema}), (req, res) => {
console.log(req.data);
});

Above will output { foo: "Foo" } for a post with the following data sent { "foo": "Foo" }, while I would expect it should print { foo: "Foo", bar: "Bar" }

Silly me, diggin a little deeper (into AJV) I realized I needed to pass useDefaults: true to the Validator instance.

Solution if anyone will ever stumble upon this issue:
const validator = new Validator({ allErrors: true, useDefaults: true });