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

openapi-typescript-validator-ext-ref

v3.2.0-external-ref-support

Published

Generate typescript with ajv validation based on openapi schemas

Downloads

46

Readme

openapi-typescript-validator

Generate typescript with ajv >= 8.0.0 validation based on openapi schemas

What does this do?

This package will convert your openapi 3.0 spec to:

  • Typescript models
  • Decoders which validate your models against a JSON schema

Example

This schema (note: also works with JSON based schema's)

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
      required: ['id']

Will convert to:

export interface User {
  id: string;
  name?: string;
}

And will generate a decoder:

// user will be of type User if the JSON is valid
const user = UserDecoder.decode(json);

If the JSON is invalid, it will throw an error:

const user = UserDecoder.decode({
  id: 1
});

// User: /id: should be string. JSON: {"id":1}

References

References als work, this schema

{
  "components": {
    "schemas": {
      "Screen": {
        "type": "object",
        "properties": {
          "components": {
            "type": "array",
            "items": { "$ref": "#/components/schemas/Component" }
          }
        },
        "required": [ "components" ]
      },

      "Component": {
        "anyOf": [
          { "$ref": "#/components/schemas/TitleComponent" },
          { "$ref": "#/components/schemas/ImageComponent" }
        ]
      },

      "TitleComponent": {
        "type": "object",
        "properties": {
          "type": {
            "type": "string",
            "enum": ["title"]
          },
          "title": {
            "type": "string"
          },
          "subtitle": {
            "type": "string",
            "nullable": true
          }
        },
        "required": [ "type", "title" ]
      },

      "ImageComponent": {
        "type": "object",
        "properties": {
          "type": {
            "type": "string",
            "enum": ["image"]
          },
          "url": {
            "type": "string"
          }
        },
        "required": [ "type", "url" ]
      }
    }
  }
}

will generate

export type Component = TitleComponent | ImageComponent;

export interface Screen {
  components: Component[];
}
export interface TitleComponent {
  type: "title";
  title: string;
  subtitle?: string | null;
}
export interface ImageComponent {
  type: "image";
  url: string;
}

Custom builder

We also created a way to define your JSON schema a bit easier. The example above can also be written as:

Example: custom-schema.js

const { anyOf, array, constant, nillable, object, string } = require('openapi-typescript-validator');

const types = {};

types.Screen = object({
  components: array('Component'),
})

types.Component = anyOf(['TitleComponent', 'ImageComponent']);

types.TitleComponent = object({
  type: constant('title'),
  title: string(),
  subtitle: nillable(string),
});

types.ImageComponent = object({
  type: constant('image'),
  url: string(),
});

module.exports = { types }

Just call generate with schemaType: custom.

See src/builder.ts for all helpers which can be used.

Getting started

Install the package

npm i openapi-typescript-validator --save-dev

We use ajv for the decoders

npm i ajv

Your tsconfig.json file will need to be able to resolve the json files.

"resolveJsonModule": true

Create a node script called generate-schemas.js


const path = require('path');
const { generate } = require('openapi-typescript-validator');

generate({
  schemaFile: path.join(__dirname, 'myswagger.yaml'),
  schemaType: 'yaml',
  directory: path.join(__dirname, '/generated')
})

and run node generate-schemas.js

Note We recommened to setup your schema configuration in a different folder than your application. E.g:

  • schemas
    • package.json which depends on this library
  • server
    • package.json with ajv depedency and ajv-formats (if you use formats)

Breaking changes

upgrading to V3

When using the custom format for your schemas. The string, boolean, number, etc helpers are now a function instead of const.

You'll need to update your schemas

// v2
object({ title: string })

// v3:
object({ title: string() })

Documentation

generate

generate can be called with GenerateOptions. See the file for more info.