@darkpatternsdigital/openapi-codegen-typescript-fetch
v0.9.0
Published
A typescript code generator for principled development using the fetch API
Downloads
147
Readme
OpenAPI Codegen for a TypeScript-friendly Fetch client
Provides an adapter layer method for @darkpatternsdigital/openapi-codegen-typescript to integrate with fetch.
npm i @darkpatternsdigital/openapi-codegen-typescript
npm i -D @darkpatternsdigital/openapi-codegen-typescript-fetch
You must also have .NET 8.0 runtime installed on your machine.
This will provide a corresponding bin to generate the typescript files. (See the @darkpatternsdigital/openapi-codegen-typescript package for command line usage details.)
openapi-codegen-typescript api.yaml api-generated/ -c
You can then create an API wrapper such as:
import { toFetchApi } from '@darkpatternsdigital/openapi-codegen-typescript-fetch';
import operations from './api-generated/operations';
export default toFetchApi(operations, fetch);
This API will use the type safety from OpenAPI along with fetch
.
Use with node-fetch
To use with node-fetch
, a fully-qualified URL must be provided. See the following example:
import fetch from 'node-fetch';
import operations from './api-generated/operations';
const baseDomain = 'http://localhost/';
const fetchImpl: FetchImplementation<unknown> = (url, params) => {
return fetch(new URL(url, baseDomain), params);
};
const fetchApi = toFetchApi(operations, fetchImpl);
Ensure you have a compatible version of
node-fetch
installed.Add a
types.d.ts
file (or other.d.ts
file to be picked up by TypeScript in your Node sections) to your project with the following global type declarations:type FormData = typeof import('formdata-polyfill/esm.min.js').FormData; type Headers = import('node-fetch').Headers; type Blob = NodeJS.ReadableStream;