Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rewrite doesn't always work #362

Open
zoellner opened this issue Mar 30, 2022 · 0 comments
Open

Rewrite doesn't always work #362

zoellner opened this issue Mar 30, 2022 · 0 comments

Comments

@zoellner
Copy link

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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant