0

I'm using AJV (Another Json schema validator) on NodeJs.

I've the following schema

var schema = {
    "$id": "testSchema.json",
    "type": "object",
    "$schema": "http://json-schema.org/draft-06/schema#",
    "additionalProperties": false,
    "properties": {
        "userId": {
            "type": "integer"
        },
        "userName": {
            "type": "string"
        },
        "uniqueID": {
            "type": "integer"
        }
    }
}

I need to overwrite unqiueID property by a value that I could somehow pass to Json schema or AJV. I think the above can be done using AJV addKeyword method, tried using it but failed because I don't know how to manipulate (and return) data value from AJV custom keywords. Is possible to modify data with AJV ? or are there any other possible ways to do it?? Thank you!

Kshateesh
  • 571
  • 1
  • 8
  • 21

1 Answers1

2

You can create a custom keyword with function that will do whatever your want to data.

var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true});

ajv.addKeyword('my_id_rewrite', {
  type: 'object',
  compile: function (sch, parentSchema) {
            return function (data) { 
                console.log(data)
                data['my_id']=parentSchema.my_id_rewrite;
                return true; 
            }
  }
});

var schema = { "my_id_rewrite": 2 };
var validate = ajv.compile(schema);
o = {"my_id":1}
console.log(validate(o)); // true
console.log(o); // Object {my_id: 2}

https://runkit.com/embed/cxg0vwqazre3

vearutop
  • 3,924
  • 24
  • 41
  • 1
    @bertonc96 - Also see https://github.com/ajv-validator/ajv/issues/141#issuecomment-270692820 - a post by the ajv author about coercing/rewriting data. (BTW the above snippet works in the sandbox the poster provided a link to.) – Craig Hicks Feb 04 '21 at 00:20
  • 1
    @bertonc96 - And this : https://github.com/ajv-validator/ajv/issues/399#issuecomment-275566352 – Craig Hicks Feb 04 '21 at 00:22