JSPM

  • Created
  • Published
  • Downloads 18310
  • Score
    100M100P100Q136962F
  • License MIT

Generate SWR hooks from OpenAPI schemas

Package Exports

  • swr-openapi
  • swr-openapi/dist/index.js
  • swr-openapi/dist/index.mjs

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (swr-openapi) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

swr-openapi

Generate swr hooks using OpenAPI schemas

npm license

Installation

npm install swr openapi-fetch swr-openapi
npm install --save-dev openapi-typescript

Setup

For each Open API schema you want to use, run the following command to transform each schema into TypeScript types:

npx openapi-typescript "https://sandwiches.example/openapi/json" --output ./types/sandwich-schema.ts

Once you have types for your API saved, create an API client:

// sandwich-api.ts
import type * as SandwichSchema from "./types/sandwich-schema";

export const sandwichAPI = createClient<SandwichSchema.paths>({
  baseUrl: "https://sandwiches.example",
});

Now, initialize a hook factory for that API:

// sandwich-api.ts
import { makeHookFactory } from "swr-openapi";
import type * as SandwichSchema from "./types/sandwich-schema";

export const sandwichAPI = createClient<SandwichSchema.paths>({
  baseUrl: "https://sandwiches.example",
});

// 👇👇👇
const makeHook = makeHookFactory<SandwichSchema.paths>(sandwichAPI);

Info When working with multiple APIs, you can customize the name of each hook factory to suite your application:

const fooAPI = createClient(...);
const makeFooHook = makeHookFactory(fooAPI);

const barAPI = createClient(...);
const makeBarHook = makeHookFactory(barAPI);

With setup now out of the way, you can define the actual hooks used by your application:

// sandwich-api.ts
import { makeHookFactory } from "swr-openapi";
import type * as SandwichSchema from "./types/sandwich-schema";

export const sandwichAPI = createClient<SandwichSchema.paths>({
  baseUrl: "https://sandwiches.example",
});

const makeHook = makeHookFactory<SandwichSchema.paths>(sandwichAPI);

// 👇👇👇
export const useSandwichesForUser = makeHook("/user/{userId}/sandwiches");
export const useSandwiches = makeHook("/sandwiches");

Now, you can call the hooks elsewhere in your application:

import { useSandwiches, useSandwichesForUser } from "./sandwich-api";

export function UserSandwiches() {
  const { data: sandwiches } = useSandwiches({
    params: {
      query: { limit: 10 },
    },
  });

  const { data: userSandwiches } = useSandwichesForUser({
    params: {
      path: { userId: "user-123" },
    },
  });

  // ...
}