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

@adbros/typegen

v3.0.0

Published

A simple generator of TypeScript types from OpenAPI docs

Downloads

709

Readme

Typegen

A simple generator of TypeScript types from OpenAPI docs.

Installation

  • Install the NPM package: npm install --save-dev @adbros/typegen.
  • Create a typegen.config.mjs file and export a valid config object from it. See Configuration (below) for details.

Usage

Each time the OpenAPI doc changes, run npx typegen in the directory containing typegen.config.mjs.

Configuration

The typegen.config.mjs file should be present in the current working directory when running the typegen utility. (Usually, it makes most sense for it to reside in the project's root directory -- next to package.json, tsconfig.json, etc.).

The config object exported from typegen.config.mjs (using ESM default export) should have the following properties:

  • inputDoc (required) -- A string containing the path to the input OpenAPI 3.0.x doc.
  • outputDir (required) -- A string containing the path to the output directory.
  • hooks -- An optional child config object containing convenience funtions to be called before/after the type generation itself. Both functions are optional. Both are called with zero arguments. Both may return a promise; the program's execution will be blocked until the promise's resolution. Both may throw or return an eventually rejected promise, in which case the program will be prematurely terminated with a nonzero exit code.
    • before -- Called before the input doc is loaded. Useful e.g. for fetching the doc from an external source, generating the doc from other data, performing custom validation on the doc (and throwing/rejecting on failure to prevent the type generation itself), etc.
    • after -- Called after the type generation is finished and the files written. Useful e.g. for custom post-processing of the generated files.
  • endpoints -- An optional child config object containing options related to the rendering of endpoints as arbitrary TypeScript constructs. If not given, endpoints.ts is not generated at all. If given, it must contain:
    • renderEach -- A function, called for each endpoint (i.e. each path-method pair), that maps available info about the given endpoint to a string containing arbitrary TypeScript code. If a nullish value is returned from the function instead, the given endpoint is excluded from the output. The function is always called with a single argument -- an object containing the following properties:
      • path (string) -- the path as specified in the input doc;
      • method (string) -- the name of the HTTP method in lower case, e.g. post;
      • pathType (string) -- a string literal type or template literal type describing the path including path parameters, e.g. `/customer/${number}/invoices`;
      • requestType (string) -- the type of the request body, e.g. Invoice;
      • responseType (string) -- the type of the response body for status code 200, e.g. { invoices: Invoice[]; totalCount: number };
      • paramsType (string) -- the type describing an object, where each property corresponds to a single query parameter accepted by the endpoint, e.g. GetInvoicesParams (defined in params.ts as e.g. { limit: number; offset: number });
      • paramsExpected (boolean) -- whether there is at least one query parameter accepted by the endpoint;
      • paramsRequired (boolean) -- whether there is at least one query parameter required by the endpoint;
      • bodyExpected (boolean) -- whether the endpoint expects a request body;
      • bodyReturned (boolean) -- whether the endpoint returns a body within each response with status code 200.
    • renderModule -- A function which maps the concatenated output of renderEach calls to a string containing the final TypeScript module. It takes an object with the sole property content.

Example

The following config defines the generation of a valid subtype of an Axios instance, which only permits calls to existing endpoints using overloaded method signatures. This is useful because:

  • calls to nonexistent endpoints are disallowed;
  • correct request bodies/parameters are enforced;
  • the return type -- corresponding to the matching endpoint's response type -- is automatically inferred for each valid call.
export default {
  inputDoc: 'path/to/openapi.yaml',
  outputDir: 'path/to/output/directory'
  endpoints: {
    renderModule: ({ content }) => `export type Api = { ${content} };`,
    renderEach: ({
      method,
      pathType,
      requestType,
      responseType,
      paramsType,
      paramsExpected,
      paramsRequired,
    }) => {
      switch (method) {
        case 'get':
          return paramsExpected
            ? `${method}(
              path: ${pathType},
              config${paramsRequired ? '' : '?'}:
                { params: ${paramsType} },
            ): Promise<{ data: ${responseType} }>;`
            : `${method}(
              path: ${pathType},
            ): Promise<{ data: ${responseType} }>;`;
        case 'post':
        case 'put':
          return `${method}(
            path: ${pathType},
            body: ${requestType},
          ): Promise<{ data: ${responseType} }>;`;
        default:
          return `${method}(
            path: ${pathType},
          ): Promise<{ data: ${responseType} }>;`;
      }
    },
  },
};