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

oas-to-ts

v0.3.0

Published

Convert an OpenAPI specifcation document to typescript types

Downloads

74

Readme

oas-to-ts

npm version build Coverage Status code style: prettier types MIT license

Convert an OpenAPI specifcation document to typescript types

Introduction

Supports a design-first workflow that only generates types (no runnable code):

  1. Edit the openapi.yaml document manually.
  2. Genereate types automatically (but no runnable code).
  3. Write code manually to implement the types.
  4. When changing the API restart at item 1.

The generated type is a full description of the OpenAPI specification document. The structure is as close as possible to the orinal document. Any meta-data is removed and JSON schemas are replaced with typescript types.

From the generated type we can map other types. For example it is possible to map typed handler functions for the server and typed request functions for the client.

How to install

yarn add -D oas-to-ts

How to use

node ./packages/server-infra/oas-to-ts/lib/cli.js -i ./packages/server/external-api/src/schema.yml -o ./packages/server/external-api/src/schema.ts

Example

For this openapi.yam:

openapi: 3.0.0
info:
  title: Unit Configuration API
  description: Allows to create, read, update, delete, and search of unit configurations.
  version: 0.1.0

paths:
  /units:
    get:
      summary: Returns a list of units.
      responses:
        "200":
          description: A JSON array of unit names
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/UnitList"
    post:
      summary: Creates a new unit.
      requestBody:
        $ref: "#/components/requestBodies/UnitBody"
      responses:
        "201":
          description: Created

  /units/{unitId}:
    get:
      summary: Get a unit by ID
      parameters:
        - $ref: "#/components/parameters/unitId"
        - in: query
          name: "unitId"
          schema:
            type: integer
      responses:
        "200":
          description: A JSON array of unit names
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Unit"
        "404":
          description: Not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

components:
  schemas:
    UnitList:
      type: array
      items:
        $ref: "#/components/schemas/Unit"
    Unit:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
    Error:
      type: object
      properties:
        code:
          type: integer
        description:
          type: string
  parameters:
    unitId:
      in: path
      name: unitId
      schema:
        type: integer
      required: true
      description: ID of the unit to get
  requestBodies:
    UnitBody:
      description: Creates a new unit.
      required: true
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Unit"

This type will be genereated:

/**
 * This type represents the whole OpenAPI spec document
 * We can pick types from there to build handlers, request etc.
 */
export interface Spec {
  readonly paths: {
    readonly "/units": {
      readonly get: {
        readonly parameters: {};
        readonly responses: {
          readonly "200": {
            readonly content: {
              readonly "application/json": Spec["components"]["schemas"]["UnitList"];
            };
          };
        };
      };
      readonly post: {
        readonly parameters: {};
        readonly requestBody: Spec["components"]["requestBodies"]["UnitBody"];
        readonly responses: {
          readonly "201": {};
        };
      };
    };
    readonly "/units/{unitId}": {
      readonly get: {
        readonly parameters: {
          readonly path: {
            readonly unitId: Spec["components"]["parameters"]["path"]["unitId"];
          };
        };
        readonly responses: {
          readonly "404": {
            readonly content: {
              readonly "application/json": Spec["components"]["schemas"]["Error"];
            };
          };
          readonly "200": {
            readonly content: {
              readonly "application/json": Spec["components"]["schemas"]["Unit"];
              readonly "text/plain": string; // for testing
            };
          };
        };
      };
    };
  };
  readonly components: {
    readonly schemas: {
      readonly UnitList: readonly Spec["components"]["schemas"]["Unit"][];
      readonly Unit: { readonly id?: number; readonly name?: string };
      readonly Error: { readonly code?: number; readonly description?: string };
    };
    readonly parameters: {
      readonly path: {
        readonly unitId: number;
      };
    };
    readonly requestBodies: {
      readonly UnitBody: {
        readonly content: {
          readonly "application/json": Spec["components"]["schemas"]["Unit"];
        };
      };
    };
  };
}

Then we can use the type mappers to create handler functions:

// The Context is whatever you want, similar to Context in graphql resolvers
export type HandlerFns<Context> = HandlerFnsFromRootSpec<Spec, Context>;

export const pathOperationHandlers: HandlerFns<Context> = {
  "/units": {
    get: async (ctx, parameters) => {
      console.log(ctx, parameters);
      const theUnits = ctx.db.getUnits();
      return {
        httpCode: "200",
        contentType: "application/json",
        content: theUnits,
      };
    },
    post: async (_ctx, _parameters) => {
      // console.log(ctx, parameters);
      return {
        httpCode: "201",
      };
    },
  },
  "/units/{unitId}": {
    get: async (ctx, parameters) => {
      console.log(ctx, parameters);
      const theUnits = ctx.db.getUnits();
      const foundUnit = theUnits.find((u) => u.id === parameters.path.unitId);
      if (foundUnit) {
        return {
          httpCode: "200",
          contentType: "application/json",
          content: foundUnit,
        };
      } else {
        return {
          httpCode: "404",
          contentType: "application/json",
          content: {},
        };
      }
    },
  },
};

After mapping the types can be hard to visualize in vscode. They look something like this:

export type PathOperationFns<Context> = {
  readonly "/units": {
    readonly get: (
      ctx: Context,
      parameters: Spec["paths"]["/units"]["get"]["parameters"]
    ) => Promise<HandlerResponseFromSpec<Spec["paths"]["/units"]["get"]["responses"]>>;
    readonly post: (
      ctx: Context,
      parameters: Spec["paths"]["/units"]["post"]["parameters"],
      requestBody: Spec["paths"]["/units"]["post"]["requestBody"]
    ) => Promise<HandlerResponseFromSpec<Spec["paths"]["/units"]["post"]["responses"]>>;
  };
  readonly "/units/{unitId}": {
    readonly get: (
      ctx: Context,
      parameters: Spec["paths"]["/units/{unitId}"]["get"]["parameters"]
    ) => Promise<HandlerResponseFromSpec<Spec["paths"]["/units/{unitId}"]["get"]["responses"]>>;
  };
};

Using with fastify

There is a built-in fastify adapter that can be used with the generated types.

Future work

  • Perhaps we should generate handler funciton types explicitly instead of mapping them. Mapping is technically better since the generated type can be simple and support many types of mapping. But generating explicit types makes it easier to read/visualize the types.

Notes about design-first approach vs code-first

https://apisyouwonthate.com/blog/theres-no-reason-to-write-openapi-by-hand/ https://apisyouwonthate.com/blog/api-design-first-vs-code-first

How to publish

yarn version --patch
yarn version --minor
yarn version --major