hyperjump-io / json-schema

JSON Schema Validation, Annotation, and Bundling. Supports Draft 04, 06, 07, 2019-09, 2020-12, OpenAPI 3.0, and OpenAPI 3.1
https://json-schema.hyperjump.io/
MIT License
216 stars 22 forks source link

How to make a schema from inline? #19

Closed KidLinus closed 1 year ago

KidLinus commented 1 year ago

I really can't figure out how to just import a schema that's defined inline. How do I load a simple schema and then execute it using this library without using abolute paths or host it online?

const JsonSchema = require("@hyperjump/json-schema");

const sch = JSON.parse(`{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "https://somesite.com/schema/base",
    "type": "object",
    "title": "This is the outer doc",
    "properties": {
        "version": { "type": "string" },
        "info": { "$ref": "/schema/info" }
    },
    "required": ["version", "info"],
    "$defs": {
        "info": {
            "$id": "/schema/info",
            "$schema": "https://json-schema.org/draft/2020-12/schema",
            "type": "object",
            "properties": {
                "issuer": { "type": "string" }
            },
            "required": ["issuer"]
        }
    }
}`)

const input = {
    "version": "test",
    "info": { "issuer": "test" },
}

JsonSchema.validate(sch, input).then(console.log).catch(console.error)
jdesrosiers commented 1 year ago

JsonSchema.validate doesn't take a raw schema, it takes a SchemaDocument instance. You need to use JsonSchema.add to load your schema into the system, then use JsonSchema.get to get a SchemaDocument for that schema.

JsonSchema.add(sch);
const schema = await JsonSchema.get("https://somesite.com/schema/base");
const output = await JsonSchema.validate(schema, input);

Sorry that was confusing. I have considered having JsonSchema.validate optionally take a URI instead of a SchemaDocument. That would cut down on the boilerplate code in cases like this.