@kiyoshiro/openapi-typescript-any-client
v0.1.1
Published
> Create type-safe fetcher with any fetch client, such as axios, ky and so on.
Downloads
3
Readme
openapi-typescript-any-client
Create type-safe fetcher with any fetch client, such as axios, ky and so on.
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 },
});