ConsumerDataStandardsAustralia / dsb-schema-tools

MIT License
0 stars 4 forks source link

Can this be used with ajv directly (without postman)? #36

Open jasonsultana opened 1 month ago

jasonsultana commented 1 month ago

Hypothesis

Schema files should be able to be used with ajv directly in NodeJS scripts, not just within postman.

Description

I've tried running the following:

const schema = require('../1.31.0/schemas/banking/BankingAccountV2.json');
const bankingCategorySchema = require('../1.31.0/schemas/banking/BankingProductCategory.json');

const Ajv = require("ajv")
const ajv = new Ajv({
    strict: false,
});

ajv.addSchema(bankingCategorySchema);

const validate = ajv.compile(schema);

But this produces MissingRefError: can't resolve reference BankingProductCategory.json from id #.

I've also tried:

const schema = require('../1.31.0/schemas/banking/BankingAccountV2.json');
const bankingCategorySchema = require('../1.31.0/schemas/banking/BankingProductCategory.json');

const Ajv = require("ajv")
const ajv = new Ajv({
    strict: false,
    schemas: [
        schema,
        bankingCategorySchema
    ]
});

const validate = ajv.compile(schema);

But this produces: Error: schema with key or id "" already exists.

Keep in mind that I'm just executing a plain-old node script via node ./index.js.

Am I doing something wrong here, or are we not expecting the schemas to be compiled with ajv in Node scripts outside of the postman environment?

Thanks heaps!

Available Options

tom-schier commented 1 month ago

@jasonsultana I think this is more a question on understanding the Ajv validator.

When you call ajv.addSchema() without the second argument it will use the id of the schema as key (see docs here) We don’t have the id in our schemas. We will keep that in mind as a future improvement.

What you are effectively doing is adding two schemas with the same key ("").   You would need to do something like this

addSchema(bankingCategorySchema, “BankingCategory”)
addSchema(schema, “BankingAccountV2”)

ie add a value/key pair. You could use anything as a key. It is that key which you will need later when validating your json data against a schema   Your second approach is effectively doing the sama as your first approach, ie call addSchema with a single argument. Hope this helps. You might want to read more in the Ajv docs