• Stars
    star
    137
  • Rank 266,121 (Top 6 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created over 2 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐Ÿฅฌ OpenAPI to React Query (or SWR) & Axios

npm License PR Test

๐Ÿฅฌ Rapini - OpenAPI to React Query (or SWR) & Axios

Rapini is a tool that generates React Query (or SWR) hooks, Axios requests and Typescript types, based on an OpenAPI spec file. The generated code is packaged conveniently so that it can be published as a package on any NPM registry.

Features

  • ๐Ÿšด Generates axios calls for every endpoint, with typed payload.
  • ๐ŸŒ๏ธ Generates custom react hooks that use React Query's useQuery and useMutation hooks for each axios call. Optional to generate custom hooks that use SWR's useSWR hook.
  • ๐Ÿšฃ Generates query keys for every hook.
  • ๐Ÿ‹๏ธ Generates strong typescript types for all inputs, outputs, and options.

Getting Started

Rapini is a CLI tool so you can execute the remote npm package directly for convenience

npx rapini [library] [options]

eg:

# For React Query V3
npx rapini react-query -p path/to/openapi.yaml

# For TanStack Query 4
npx rapini react-query v4 -p path/to/openapi.yaml

# For TanStack Query 5
npx rapini react-query v5 -p path/to/openapi.yaml

# For SWR
npx rapini swr -p path/to/openapi.yaml

This will generate the package code based on an OpenAPI file at path/to/openapi.yaml. The outputted code will be packaged in a way to just publish it as your own NPM package and then import it in your React project.

CLI Arguments & Options

rapini help outputs the following:

Usage: rapini [options] [command]

Generate a package based on OpenAPI

Options:
  -V, --version                    output the version number
  -h, --help                       display help for command

Commands:
  react-query [options] [version]  Generate a Package for TanStack Query V4 or React Query V3
  swr [options]                    Generate a Package for SWR (stale-while-revalidate)
  help [command]                   display help for command

rapini help react-query outputs the following:

Usage: rapini react-query [options] [react-query-version]

Generate a Package for TanStack Query V4 or V5, or legacy React Query V3

Options:
  -p, --path <path>                          Path to OpenAPI file
  -n, --name [name]                          Name to use for the generated package (default: "rapini-generated-package")
  -pv, --package-version [version]           Semver version to use for the generated package (default: "1.0.0")
  -o, --output-dir [directory]               Directory to output the generated package (default: "rapini-generated-package")
  -b, --base-url [url]                       Prefix every request with this url
  -r, --replacer [oldString] [newString...]  Replace part(s) of any route's path with simple string replacements. Ex: `-r /api/v1 /api/v2` would replace the v1 with v2 in every route
  -h, --help                                 display help for command

rapini help swr outputs the following:

Usage: rapini swr [options]

Generate a Package for SWR (stale-while-revalidate)

Options:
  -p, --path <path>                          Path to OpenAPI file
  -n, --name [name]                          Name to use for the generated package (default: "rapini-generated-package")
  -pv, --package-version [version]           Semver version to use for the generated package (default: "1.0.0")
  -o, --output-dir [directory]               Directory to output the generated package (default: "rapini-generated-package")
  -b, --base-url [url]                       Prefix every request with this url
  -r, --replacer [oldString] [newString...]  Replace part(s) of any route's path with simple string replacements. Ex: `-r /api/v1 /api/v2` would replace the v1 with v2 in every route
  -h, --help                                 display help for command

Example Usage

Let's say you have an OpenAPI file that looks like this one.

Once you run the CLI tool to generate the React Query code, you can then cd into the generated directory, run npm install && npm run build then npm publish with your own package name to publish it to your own registry, then import and use it like this:

import { initialize } from "your-custom-package";
import { axiosInstance } from "./your-custom-axios-instance";

// Can even import the generated Typescript Types if needed
import type { Pet } from "your-custom-package";

const config = initialize(axiosInstance);

const { usePets } = config.queries;

const MyComponent = () => {
  const { data, isLoading, isError } = usePets();

  return (
    <ul>
      {data.pets.map((pet) => (
        <li key={pet.id}>{pet.name}</li>
      ))}
    </ul>
  );
};

You must call initialize(axiosInstance) with your custom axios instance. The return value from the initialize will give you an object with everything you need, here is the return value with examples:

import { queryKeys } from "generated-package";
// queryKeys = { pets: () => ['pets'] } ...

const rapini = initialize(axiosInstance);
rapini.queries; // { usePets, usePetById } ...
rapini.mutations; // { useUpdatePet, useDeletePet } ... if generated by SWR, there will be no property `mutations`
rapini.requests; // { pets: () => axios.get<Pet[]>(...) } ...

With Global Config

There may be times when you want extra functionality hooked into each hook's callbacks. You can do this normally by passing options to each hook, but if you want something more global - a config can be provided to the initialize function.

import { initialize, type Config } from "your-custom-package";
import type { QueryClient } from "react-query";

const config: Config = {
  mutations: {
    useCreatePet: (queryClient: QueryClient) => ({
      onSuccess: () => showSuccessNotification(),
      onError: () => showErrorNotification(),
    }),
  },
};

const rapini = initialize(axiosInstance, config);

Important Notes

  • Every request must have an operationId defined. The operationId is used in many places in the final generated code.

More Repositories

1

pratica

๐Ÿฅƒ Functional Algebraic Data Types
TypeScript
445
star
2

zodot

๐Ÿ›ก๏ธ Zod for Godot Data Validation
GDScript
36
star
3

srd

๐Ÿš€ Simple Remote Data (SRD) is a fully static land compliant implementation of the Remote Data type in TypeScript
TypeScript
29
star
4

recipe-book

Recipes Book - Made with Hugo
HTML
21
star
5

Pali

Pali - A 3D Godot TCG Multiplayer Card Game
GDScript
19
star
6

retros

๐Ÿ‚๐Ÿป Haskell based Retro board
Haskell
17
star
7

godot-polygon-generator

๐Ÿ„ Godot tool for creating simple polygon shapes using S-Curves
GDScript
14
star
8

coppa

๐Ÿ‡ A CLI tool for local development of serverless Google Cloud Functions
JavaScript
12
star
9

soften

๐ŸŒซ Base64 Image Softener
JavaScript
8
star
10

meatball

๐Ÿ Future based redux side effects
JavaScript
7
star
11

klaso

๐Ÿท A functional alternative to creating stateful React components
JavaScript
6
star
12

zucchini

๐Ÿฅ— Grocery App - Elm
Elm
5
star
13

fpjs

๐Ÿ”ฎ FPJS - Sandbox for functional programming snippets
JavaScript
4
star
14

prosciutto

๐Ÿฅ“ Functor based redux side effects
JavaScript
4
star
15

quantor

๐Ÿ’ƒ Simple SSR - JSON to HTML - API Docs
HTML
3
star
16

monjoi

MongoDB + Joi
TypeScript
2
star
17

salami

๐Ÿ’ธ Expense tracker in F#
F#
2
star
18

FortniteIngest

Microservice. Ingest data from Fortnite tracker API and save to firebase DB
JavaScript
1
star
19

fortnite-tracker

front end of the fortnite ingest
JavaScript
1
star
20

react-query-v4-bug-repro

TypeScript
1
star
21

garduino

Home garden monitoring and automation with angular/node/mongo/arduino/raspberry pi
CSS
1
star
22

quebec-covid19

COVID-19 Quebec Self Assessment Tool
Elm
1
star
23

gloria

๐Ÿ’„Gloria Github Bot
TypeScript
1
star
24

rametta

1
star
25

GarduinoAPI

Dotnet Core C# ServiceStack API
C#
1
star
26

limitor

โฑ A Future based rate limiter utility
JavaScript
1
star