0.1.1 • Published 11 months ago

@kiyoshiro/openapi-typescript-any-client v0.1.1

Weekly downloads
-
License
MIT
Repository
-
Last release
11 months ago

openapi-typescript-any-client

Create type-safe fetcher with any fetch client, such as axios, ky and so on.

codecov

demo

Usage

Install

npm i -D @kiyoshiro/openapi-typescript-any-client

Generate code

openapi-typescript-any-client ./openapi.yaml -o generated.ts

Define your own fetcher with the generated code

// fetcher.ts
import { createBaseFetcher } from "./generated";

// standard fetch
export const fetcher = createBaseFetcher((path, { method, body }) =>
  fetch("http://localhost:3000" + path, {
    method,
    body: JSON.stringify(body),
  }).then((res) => res.json())
);

// axios
export const fetcher = createBaseFetcher((path, { method, body }) =>
  axios({
    baseURL: "http://localhost:3000",
    url: path,
    method,
    data: body,
  }).then((res) => res.data)
);

// ky
export const fetcher = createBaseFetcher((path, { method, body }) =>
  ky(path, {
    prefixUrl: "http://localhost:3000",
    url: path,
    method,
    json: body,
  }).json()
);
// fetcher.ts
import { createOperationIdFetcher } from "./generated";

// standard fetch
export const fetcherObj = createOperationIdFetcher((path, { method, body }) =>
  fetch("http://localhost:3000" + path, {
    method,
    body: JSON.stringify(body),
  }).then((res) => res.json())
);

// axios
export const fetcherObj = createOperationIdFetcher((path, { method, body }) =>
  axios({
    baseURL: "http://localhost:3000",
    url: path,
    method,
    data: body,
  }).then((res) => res.data)
);

// ky
export const fetcherObj = createOperationIdFetcher((path, { method, body }) =>
  ky(path, {
    prefixUrl: "http://localhost:3000",
    url: path,
    method,
    json: body,
  }).json()
);

Use the fetcher created above (It's type-safe!)

const res = await fetcher.get("/users", {
  query: { per: 10, page: 0 },
});
// `listUsers` comes from operationId
// in your OpenAPI schema
const res = await fetcherObj.listUsers({
  query: { per: 10, page: 0 },
});
0.1.1

11 months ago

0.1.0

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago