tdegrunt / jsonschema

JSON Schema validation
Other
1.82k stars 262 forks source link

Rewrite doesn't always work #362

Open zoellner opened 2 years ago

zoellner commented 2 years ago

I want to rewrite values based on the custom format. This only works in some cases. See example below. Expected output is

'CUSTOM: Test1'
[ 'CUSTOM: Test2' ]
{ value: 'CUSTOM: Test3' }
{ value: 'CUSTOM: Test4a' }
{ value: [ 'CUSTOM: Test4b' ] }

Actual output is

'Test1'
[ 'CUSTOM: Test2' ]
{ value: 'CUSTOM: Test3' }
{ value: 'Test4a' }
{ value: [ 'CUSTOM: Test4b' ] }
const { Validator } = require('jsonschema');
const myValidator = new Validator();

const schema1 = {
  type: 'string',
  format: 'custom'
};

const schema2 = {
  type: 'array',
  items: {
    type: 'string',
    format: 'custom'
  }
};

const schema3 = {
  type: 'object',
  properties: {
    value: {
      type: 'string',
      format: 'custom'
    }
  }
};

const schema4 = {
  type: 'object',
  properties: {
    value: {
      oneOf: [
        schema1,
        schema2
      ]
    }
  }
};

const validatorOptions = {
  rewrite
};

function rewrite(instance, schema) {
  if (schema.type === 'string' && schema.format === 'custom') {
    return `CUSTOM: ${instance}`;
  }

  return instance;
}

const doc1 = 'Test1';
const doc2 = ['Test2'];
const doc3 = {value: 'Test3'};
const doc4a = {value: 'Test4a'};
const doc4b = {value: ['Test4b']};

myValidator.validate(doc1, schema1, validatorOptions);
myValidator.validate(doc2, schema2, validatorOptions);
myValidator.validate(doc3, schema3, validatorOptions);
myValidator.validate(doc4a, schema4, validatorOptions);
myValidator.validate(doc4b, schema4, validatorOptions);

console.log(doc1);
console.log(doc2);
console.log(doc3);
console.log(doc4a);
console.log(doc4b);