npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@laminarjs/json-schema

v0.15.0

Published

A lightweight a json-schema. Depends only on yaml package and node-fetch.

Downloads

3

Readme

JSON Schema

A lightweight a json-schema.

Dependencies:

  • yaml
  • axios

Supported JSON Schema drafts

  • draft-4
  • draft-5
  • draft-7
  • draft-2019-09
  • openapi3 (The json-schema variant that's used by OpenApi 3: https://swagger.io/docs/specification/data-models/keywords/)

Usage

yarn add @laminarjs/json-schema

examples/simple.ts

import { validate, Schema } from '@laminarjs/json-schema';

const schema: Schema = {
  type: 'string',
  format: 'email',
};

const value = '12horses';

validate({ schema, value }).then((result) => console.log(result.valid, result.errors));

Should output

false
[ '[value] should match email format' ]

Compare to other implementations

It is comparatively slower than the venerable Ajv but is a lot simpler and smaller. It also passes the official json-schema-org/JSON-Schema-Test-Suite.

It does not rely on any shared state or static parameters returning all the errors for a given validation operation in one result. Which was one of the reasons to develop an alternative to Ajv in the first place.

It was made as a lightweight dependency to @laminarjs/laminar framework with nice error messages.

Examples

Compile and Validate

If we assume we have those 2 http resources at the given URLs, You can compile the schema once, downloading the relevant URLs, and then use the CompiledSchema to perform any further validation without downloading and parsing the files again.

examples/compile-urls.ts

import { validate, compile } from '@laminarjs/json-schema';
import nock from 'nock';

const mainSchema = `
{
  "type": "object",
  "properties": {
    "size": {
      "type": "number"
    },
    "color": { "$ref": "https://example.com/color" }
  }
}
`;

const colorSchema = `
enum:
  - red
  - green
  - blue
`;

nock('https://example.com')
  .get('/schema')
  .reply(200, mainSchema, { 'Content-Type': 'application/json' })
  .get('/color')
  .reply(200, colorSchema, { 'Content-Type': 'application/yaml' });

compile('https://example.com/schema').then((schema) => {
  console.log(schema);

  const correct = { size: 10, color: 'red' };
  const incorrect = { size: 'big', color: 'orange' };

  const correctResult = validate({ schema, value: correct });
  console.log(correctResult.valid, correctResult.errors);

  const incorrectResult = validate({ schema, value: incorrect });
  console.log(incorrectResult.valid, incorrectResult.errors);
});

Load local files

You can also provide paths to local files to download the schema from. It it ends with "yaml" or "yml" it would be loaded as YAML, otherwise it would be parsed as JSON.

examples/validate-local-schema.ts

import { validateCompiled, validate, compile } from '@laminarjs/json-schema';
import { join } from 'path';

const schema = join(__dirname, 'color-schema.yaml');

validate({ schema, value: 'orange' }).then((result) => {
  console.log('validate', result.valid, result.errors);
});

compile({ schema }).then((compiledSchema) => {
  const result = validateCompiled({ schema: compiledSchema, value: 'red' });

  console.log('compile', result.valid, result.errors);
});

Custom error messages

You can customize error messages with formatErrors option. It gets the full validaiton with its errors, and should return an array of string error messages.

examples/format-errors.ts:(format-errors)

const formatErrors: FormatErrors = (validation) =>
  validation.errors.map((error) => ` - ${error.code} : ${error.name} \n`);

validate({ schema, value, formatErrors }).then((result) => console.log(result.valid, result.errors));

The possible error codes are:

src/validation.ts:(error-codes)

export type InvalidCode =
  | 'not'
  | 'enum'
  | 'type'
  | 'multipleOf'
  | 'minimum'
  | 'exclusiveMinimum'
  | 'maximum'
  | 'exclusiveMaximum'
  | 'pattern'
  | 'format'
  | 'false'
  | 'maxLength'
  | 'minLength'
  | 'contains'
  | 'additionalProperties'
  | 'unevaluatedProperties'
  | 'unevaluatedItems'
  | 'required'
  | 'minProperties'
  | 'maxProperties'
  | 'dependencies'
  | 'uniqueItems'
  | 'minItems'
  | 'maxItems'
  | 'oneOf'
  | 'anyOf';

Alternatively, you can set formatErrors to false and receive the raw error message objects.

examples/raw-errors.ts:(format-errors)

validate({ schema, value, formatErrors: false }).then((result) => console.log(result.valid, result.errors));
### API

**validate** validate given data with a schema. The schema can be a path to a yaml / json file, or a url to one, as well as plain old js object with the said schema.

**compile** Compile a schema by downloading any dependencies, resolving json refs or loading yaml / json files from URLs or file paths. The result can be passed to validate to skip the downloading.

**validateCompiled** You can pass the compiled schema and it will process the schema synchronously, without the use of Promises.

**ensureValid** Ensure that a given value is of a typescript type, using json-schema

**coerce** Coerce a given value, using the provided json schema.

- With type: 'json'
  This is used to convert json validated with json schema into javascript objects.
  Namely it converts all the strings with format date and date-time into Date objects.
- With type: 'query'
  To convert a value coming from a URL query string to the type you want it to be,
  for example '12' with type: 'integer' will be converted to 12 so the validation can succeed.

Additionally, we assign default values where appropriate.

### Develop

yarn yarn test