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

@codacy/oazapfts

v3.6.0-alpha.1

Published

OpenApi TypeScript client generator

Downloads

8

Readme

🍻 oazapfts!

Generate TypeScript clients to tap into OpenAPI servers.

Features

  • AST-based: Unlike other code generators oazapfts does not use templates to generate code but uses TypeScript's built-in API to generate and pretty-print an abstract syntax tree.
  • Fast: The cli does not use any of the common Java-based tooling, so the code generation is super fast.
  • Tree-shakeable: Individually exported functions allow you to bundle only the ones you actually use.
  • Human friendly signatures: The generated api methods don't leak an HTTP-specific implementation details. For example, all optional parameters are grouped together in one object, no matter whether they end up in the headers, path or query-string.

Installation

npm install oazapfts

NOTE: With version 3.0.0 oazapfts has become a runtime dependency and the generated code does no longer include all the fetch logic.

Usage

oazapfts <spec> [filename]

Options:
--exclude, -e tag to exclude
--include, -i tag to include

Where <spec> is the URL or local path of an OpenAPI or Swagger spec (in either json or yml) and <filename> is the location of the .ts file to be generated. If the filename is omitted, the code is written to stdout.

Overriding the defaults

The generated file exports a defaults constant that can be used to override the basePath, provide a custom fetch implementation or to send additional headers with each request:

import * as api from "./api.ts";
import nodeFetch from "node-fetch";

api.default.basePath = "https://example.com/api";

api.defaults.headers = {
  access_token: "secret",
};

api.defaults.fetch = nodeFetch;

Consuming the generated API

For each operation defined in the spec the generated API will export a function with a name matching the operationId. If no id is specified, a reasonable name is generated from the HTTP verb and the path.

The last argument of each function is an optional RequestOpts object that can be used to pass options to the fetch call, for example to pass additional headers or an AbortSignal to cancel the request later on.

Each function returns a Promise for an ApiResponse which is an object with a status and a data property, holding the HTTP status code and the properly typed data from the response body. Since an operation can return different types depending on the status code, the actual return type is a union of all possible responses, discriminated by their status.

Consider the following code generated from the petstore.json example:

export function getPetById(petId: number, opts?: RequestOpts) {
  return fetchJson<
    | {
        status: 200;
        data: Pet;
      }
    | {
        status: 400;
        data: string;
      }
    | {
        status: 404;
        data: string;
      }
  >(`/pet/${petId}`, {
    ...opts,
  });
}

In this case the data property is typed as Pet|string. We can use a type guard to narrow down the type to Pet:

const res = await api.getPetById(1);
if (res.status === 200) {
  const pet = res.data;
  // pet is properly typed as Pet
}
if (res.status === 404) {
  const message = res.data;
  // message is a string
} else {
  // handle the error
}

The above code can be simplified by using the handle helper:

import { handle } from "oazapfts";

await handle(api.getPetById(1), {
  200(pet) {
    // pet is properly typed as Pet
  },
  404(message) {
    // message is as string
  },
});

The helper will throw an HttpError error for any unhanled status code unless you add a default handler:

await handle(api.getPetById(1), {
  200(pet) {
    // ...
  },
  default(status, data) {
    // handle error
  },
});

Optimistic APIs

Instead of handling errors right in place we can also use the ok helper:

import { ok } from "oazapfts";

const pet = await ok(api.getPetById(1));

With this pattern pet will be typed as Pet and a HttpError will be thrown in case of an error.

You can even turn your whole API into an optimistic one:

import { optimistic } from "oazapfts";
import * as rawApi from "./api.ts";

const api = optimistic(rawApi);
const pet = await api.getPetById(1);

CLI

Since version 3.1.0 you can also use the --optimistic flag on the command line to generate an optimistic API by default.

About the name

The name comes from a combination of syllables oa (OpenAPI) and ts (TypeScript) and is pronounced 🗣 like the Bavarian O'zapt'is! (it's tapped), the famous words that mark the beginning of the Oktoberfest.

License

MIT