sagold / json-schema-library

Customizable and hackable json-validator and json-schema utilities for traversal, data generation and validation
MIT License
175 stars 18 forks source link

Cannot read properties of undefined (reading 'getRef') #15

Closed TimBo93 closed 2 years ago

TimBo93 commented 2 years ago

Hi,

thank you for your library! We are using your library in order to create default-templates based on a schema.

At this point we are facing an issue:

{
  $schema: 'http://json-schema.org/draft-04/schema#',
  version: 1.0,
  type: 'object',
  definitions: {
    saneUrl: {
      format: 'uri',
      pattern: '^https?://',
      default: 'https://localhost:8080',
    },
  },
  properties: {
    ContainerAddress: {
      $ref: '#/definitions/saneUrl',
    },
  },
}

regarding: https://www.jsonschemavalidator.net/ the schema itself should be valid.

import { Draft04 as JsonSchemaLibrary } from 'json-schema-library';

const schema = {
  $schema: 'http://json-schema.org/draft-04/schema#',
  version: 1.0,
  type: 'object',
  definitions: {
    saneUrl: {
      format: 'uri',
      pattern: '^https?://',
      default: 'https://localhost:8080',
    },
  },
  properties: {
    ContainerAddress: {
      $ref: '#/definitions/saneUrl',
    },
  },
};

export const jsonSchemaToTemplateConverter = () => {
  const data = {
    AnalyticsContainerAddress: 'https://asdf',
  };

  const jsonSchema = new JsonSchemaLibrary();
  const result = jsonSchema.getTemplate({}, schema);
  return result;
};

getTemplate throws the following exception: TypeError: Cannot read properties of undefined (reading 'getRef')

Are we missing something?

Kind regards Tim

TimBo93 commented 2 years ago

We were able to solve the issue by calling

const jsonSchema = new JsonSchemaLibrary();
jsonSchema.setSchema(schema);
return getTemplate(jsonSchema, data);

What I have reported may not a bug, but more likely a misunderstanding in the API. I was confused that it only fails when using $ref.

sagold commented 2 years ago

Hi @TimBo93 thank you for the feedback.

For resolution of ids, scopes and references a json-schema has to be compiled before being able to resolve $refs. This is probably not done in the case of getTemplate. You can compile a schema yourself using

import { compileSchema } from "json-schema-library";
const myCompiledSchema = compileSchema(mySchema);

setting the rootschema (which contains the definitions/defs) in the constructor or via setSchema will do this automatically, e.g.

const jsonSchema = new JsonSchemaLibrary(mySchema);

or

const jsonSchema = new JsonSchemaLibrary();
jsonSchema.setSchema(mySchema);

I will update the documentation about this, add the compile command to getTemplate and think about possible api improvements.

Cheers, Sascha

sagold commented 2 years ago

Documentation has been updated and latest api changes should prevent some of thise errors.