0

I wrote a schema in JavaScript because its easier, which I can simply run to turn it into JSON.

That part is all fine, but now I want to extract a sub-schema/definition because the application I want to use it with won't let me specify a JSON path for the sub-schema I'm interested.

So I tried writing a little script to pull it out:

#!/usr/bin/env node
import Ajv from 'ajv';
import Path from 'path';
const ajv = new Ajv({
    $data: true,
});
ajv.addSchema(require(Path.resolve(process.argv[2])).default,'x');
const schema = ajv.getSchema(`x#/${process.argv[3]}`).schema;
console.log(JSON.stringify(schema,null,4));

But what I get back is:

{
    "type": "object",
    "additionalProperties": false,
    "properties": {
        "name": {
            "$ref": "#/defs/Identifier"
        },
        "versions": {
            "type": "array",
            "items": {
                "$ref": "#/defs/TableVersion"
            }
        }
    },
    "required": [
        "name",
        "versions"
    ]
}

i.e., I lost the other definitions!

Are there some API methods in AJV to pull out a sub-schema without breaking all the $refs?

mpen
  • 272,448
  • 266
  • 850
  • 1,236

1 Answers1

0

I did it with a different a library.

Here's the script I came up with:

#!/usr/bin/env node
import $RefParser from 'json-schema-ref-parser';
import Path from 'path';

async function main() {
    const parser = new $RefParser();
    const [file,$ref] = process.argv[2].split('#');
    let rawSchema = require(Path.resolve(file));
    if(rawSchema.__esModule) {
        rawSchema = rawSchema.default;
    }
    let schema = await parser.dereference(rawSchema);
    if($ref) {
       schema = await parser.$refs.get('#'+$ref); 
    }
    console.log(JSON.stringify(schema,null,4));
}

main().catch(err => {
    process.stderr.write(`${err}\n`);
    process.exit(1);
});

Usage:

node export-schema.js table.schema.js#/defs/Table > table.schema.json
mpen
  • 272,448
  • 266
  • 850
  • 1,236