Search code examples
javascriptnode.jsjsonschemajson-schema-validatorajv

Pass value to Json schema Definition


I'm using AJV Schema validator on NodeJS and wish to add userID from sessionObject to every incoming payload so that I can store userID for each transaction.

I wish to know if that can be done in json schemas.

sample Incoming Client payload -

Client: {
Client_Id: 12,
ClientName: 'jon',
Address: [{
Address_Id: 22,
Street: 'Sesimi Street',
City: 'Mumbai'
}
],
Contact: [{
Contact_Id: 23,
Phone: 11111111,
Email: "[email protected]"}]

Desired object post schema Validation -

    Client: {
        Client_Id: 12,
        ClientName: 'jon',
        UserId: 12121,
        Address: [{
        Address_Id: 22,
        Street: 'Sesimi Street',
        City: 'Mumbai',
        UserId: 12121
        }
        ],
        Contact: [{
        Contact_Id: 23,
        Phone: 11111111,
        Email: "[email protected]",
        UserId: 12121
}]

Since incoming payloads are huge, I believe it would be best to do assignments at schema validation point instead of doing recursive operations inside of my application. I'm open to suggestions. Thank you


Solution

  • You can try useDefaults feature of AJV.

    var ajv = new Ajv({ useDefaults: true });
    var schema = {
      "type": "object",
      "properties": {
        "ClientName": { "type": "string" },
        "UserId": { "type": "integer", "default": 12121 }
      }
    };
    
    var data = { "ClientName": "jon" };
    
    var validate = ajv.compile(schema);
    
    console.log(validate(data)); // true
    console.log(data); // { "ClientName": "jon", "UserId": 12121 }
    

    To have flexibility on default value you can use dynamicDefaults with callback function. Example:

    var uuid = require('uuid');
    
    function getUuid(args) {
      var version = 'v' + (arvs && args.v || 4);
      return function() {
        return uuid[version]();
      };
    }
    
    var definition = require('ajv-keywords').get('dynamicDefaults').definition;
    definition.DEFAULTS.uuid = getUuid;
    
    var schema = {
      dynamicDefaults: {
        id1: 'uuid', // v4
        id2: { func: 'uuid', v: 4 }, // v4
        id3: { func: 'uuid', v: 1 } // v1
      }
    };