Package Exports
- swr-openapi
Readme
swr-openapi
Generate swr hooks from OpenAPI schemas
Installation
For npm:
npm install swr-openapiFor yarn:
yarn add swr-openapiFor pnpm:
pnpm add swr-openapiAdditionally, please ensure you have the following peer dependencies installed:
Dependencies
swr@^v2.0.0-beta.3(currently, v2.0.0-beta.3 or higher is required)react@^18.0.0react-dom@^18.0.0
npm install swr@^v2.0.0-beta.3 react@^18.0.0 react-dom@^18.0.0Dev Dependencies
openapi-typescript@^5.4.0typescript@^4.0.0
npm install --save-dev openapi-typescript@^5.4.0 typescript@^4.0.0How to Use
First, follow the directions for openapi-typescript to generate TypeScript types for a given API.
In the following example, we will assume that types for a "Pet Store" API have been generated at ./types/pet-store.d.ts.
import { SWRApiFactory } from "swr-openapi";
import { Paths as PetStorePaths }from "./types/pet-store";
// Create factory for the API
const petStoreService = new SWRApiFactory<PetStorePaths>({
baseURL: "https://example.com/api/petstore",
});
// Create SWR hooks for specific endponts
export [usePets] = petStoreService.makeHook("/pets");
export [usePet] = petStoreService.makeHook("/pets/{petId}");
export [usePetImages] = petStoreService.makeHook("/pets/{petId}/images");
// Call hooks with arguments
function PetList() {
const { data: pets } = usePets();
// Render list of pets (`pets` is fully type-safe!)
}
function PetProfile() {
const { data: pet } = usePet({ petId: 'pet-123' });
const { data: petImages } = usePetImages(); // <-- Type Error: Missing `petId` argument
// Render pet profile
}The SWRApiFactory class accepts all arguments that are supported by openapi-typescript-fetch in addition to other library features like middleware and typed error handling.