• Stars
    star
    261
  • Rank 156,630 (Top 4 %)
  • Language
    TypeScript
  • Created over 2 years ago
  • Updated about 2 months ago

Reviews

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

Repository Details

Node.js library that generates React Query (also called TanStack Query) hooks based on an OpenAPI specification file.

OpenAPI React Query Codegen

Node.js library that generates React Query (also called TanStack Query) hooks based on an OpenAPI specification file.

Features

  • Supports generation of custom react hooks that use React Query's useQuery and useMutation hooks
  • Supports generation of query keys for query caching
  • Supports the option to use pure TypeScript clients generated by @hey-api/openapi-ts

Install

$ npm install -D @7nohe/openapi-react-query-codegen

Register the command to the scripts property in your package.json file.

{
  "scripts": {
    "codegen": "openapi-rq -i ./petstore.yaml -c axios"
  }
}

You can also run the command without installing it in your project using the npx command.

$ npx --package @7nohe/openapi-react-query-codegen openapi-rq -i ./petstore.yaml -c axios

Usage

$ openapi-rq --help

Usage: openapi-rq [options]

Generate React Query code based on OpenAPI

Options:
  -V, --version              output the version number
  -i, --input <value>        OpenAPI specification, can be a path, url or string content (required)
  -o, --output <value>       Output directory (default: "openapi")
  -c, --client <value>       HTTP client to generate [fetch, xhr, node, axios, angular] (default: "fetch")
  --request <value>          Path to custom request file
  --useDateType              Use Date type instead of string for date types for models, this will not convert the data to a Date object
  --enums                    Generate JavaScript objects from enum definitions?
  --base <value>             Manually set base in OpenAPI config instead of inferring from server value
  --serviceResponse <value>  Define shape of returned value from service calls ['body', 'generics', 'response']
  --operationId              Use operation ID to generate operation names?
  --lint                     Process output folder with linter?
  --format                   Process output folder with formatter?
  -h, --help                 display help for command

Example Usage

Command

$ openapi-rq -i ./petstore.yaml

Output directory structure

- openapi
  - queries
    - index.ts <- main file that exports common types, variables, and hooks
    - common.ts <- common types
    - queries.ts <- generated query hooks
    - suspenses.ts <- generated suspense hooks
  - requests <- output code generated by @hey-api/openapi-ts

In your app

// App.tsx
import { usePetServiceFindPetsByStatus } from "../openapi/queries";
function App() {
  const { data } = usePetServiceFindPetsByStatus({ status: ["available"] });

  return (
    <div className="App">
      <h1>Pet List</h1>
      <ul>
        {data?.map((pet) => (
          <li key={pet.id}>{pet.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

You can also use pure TS clients.

import { useQuery } from "@tanstack/react-query";
import { PetService } from "../openapi/requests/services";
import { usePetServiceFindPetsByStatusKey } from "../openapi/queries";

function App() {
  // You can still use the auto-generated query key
  const { data } = useQuery({
    queryKey: [usePetServiceFindPetsByStatusKey],
    queryFn: () => {
      // Do something here
      return PetService.findPetsByStatus(["available"]);
    },
  });

  return <div className="App">{/* .... */}</div>;
}

export default App;

You can also use suspense hooks.

// App.tsx
import { useDefaultClientFindPetsSuspense } from "../openapi/queries/suspense";
function ChildComponent() {
  const { data } = useDefaultClientFindPetsSuspense({ tags: [], limit: 10 });

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

function ParentComponent() {
  return (
    <>
      <Suspense fallback={<>loading...</>}>
        <ChildComponent />
      </Suspense>
    </>
  );
}

function App() {
  return (
    <div className="App">
      <h1>Pet List</h1>
      <ParentComponent />
    </div>
  );
}

export default App;

License

MIT

More Repositories

1

laravel-typegen

The library lets you generate TypeScript types from your Laravel code
TypeScript
74
star
2

laravel-zodgen

The library lets you generate Zod schemas from Laravel FormRequests
TypeScript
37
star
3

react-native-typewriter-effect

Typing animation library for React Native
TypeScript
6
star
4

slack-bolt-timetree-app

TimeTree for Slack
JavaScript
6
star
5

openapi-mock-json-generator

Node.js library that generates mock API responses from an OpenAPI specification file.
TypeScript
6
star
6

docker-lessons

Docker็ ”ไฟฎ็”จ่ณ‡ๆ–™
Dockerfile
6
star
7

inertia-vue-form

Validation Form Helper Library for Inertia and Vue
TypeScript
4
star
8

app-store-connect-api-client

App Store Connect API client for Node.js
TypeScript
3
star
9

react-realtime-cursor

Figma-like cursor chat for React
TypeScript
2
star
10

remark-alerts

remark plugin to support GitHub-style alerts
TypeScript
2
star
11

vite-plugin-openapi-typescript-codegen

OpenAPI Typescript Codegen for Vite
TypeScript
2
star
12

vite-plugin-vue-marked

๐Ÿ“ Vite plugin for converting Markdown to Vue
TypeScript
2
star
13

laravel-docker-template

1
star
14

expo-zxing

ZXing module for Expo
Java
1
star
15

laravel-inertia-vue-app

Laravel9 + Inertia + Vue3 + TypeScript
PHP
1
star
16

play-console-report-client

Node.js library for getting report data from Google Play Console
TypeScript
1
star
17

ruby-parser

Ruby parser for Node.js written in Rust
Rust
1
star
18

remark-link-to-card

remark plugin to convert text links to link cards
TypeScript
1
star
19

pdf-paginator

A CLI to add page numbers to a PDF.
JavaScript
1
star
20

expo-felica-reader

Expo FeliCa reader module
Java
1
star
21

nestjs-slides

JavaScript
1
star