|
| 1 | +# OpenAPI React Query Codegen |
| 2 | + |
| 3 | +> Node.js library that generates [React Query (also called TanStack Query)](https://tanstack.com/query) hooks based on an OpenAPI specification file. |
| 4 | +
|
| 5 | +## Features |
| 6 | + |
| 7 | +- Supports generation of custom react hooks that use React Query's `useQuery` and `useMutation` hooks |
| 8 | +- Supports the option to use pure TypeScript clients generated by [OpenAPI Typescript Codegen](https://github.com/ferdikoomen/openapi-typescript-codegen) |
| 9 | + |
| 10 | +## Install |
| 11 | + |
| 12 | +``` |
| 13 | +$ npm install -D @7nohe/openapi-react-query-codegen |
| 14 | +``` |
| 15 | + |
| 16 | +## Usage |
| 17 | + |
| 18 | +``` |
| 19 | +$ openapi-rq --help |
| 20 | +
|
| 21 | + Usage: openapi-rq [options] |
| 22 | +
|
| 23 | + Generate React Query code based on OpenAPI |
| 24 | +
|
| 25 | + Options: |
| 26 | + -V, --version output the version number |
| 27 | + -p, --path <path> Path to OpenAPI file |
| 28 | + -o, --output-dir [directory] Directory to output the generated package (default: "openapi") |
| 29 | + -h, --help display help for command |
| 30 | +``` |
| 31 | + |
| 32 | +## Example Usage |
| 33 | + |
| 34 | +### Command |
| 35 | + |
| 36 | +``` |
| 37 | +$ openapi-rq -p ./petstore.yaml |
| 38 | +``` |
| 39 | + |
| 40 | +### Output directory structure |
| 41 | + |
| 42 | +``` |
| 43 | +- openapi |
| 44 | + - queries |
| 45 | + - index.ts <- custom react hooks |
| 46 | + - requests <- output code generated by OpenAPI Typescript Codegen |
| 47 | +``` |
| 48 | + |
| 49 | +### In your app |
| 50 | + |
| 51 | +```tsx |
| 52 | +// App.tsx |
| 53 | +import { |
| 54 | + usePetServiceFindPetsByStatus, |
| 55 | +} from "../openapi/queries"; |
| 56 | +function App() { |
| 57 | + const { data } = usePetServiceFindPetsByStatus({ status: ["available"] }); |
| 58 | + |
| 59 | + return ( |
| 60 | + <div className="App"> |
| 61 | + <h1>Pet List</h1> |
| 62 | + <ul> |
| 63 | + {data?.map((pet) => ( |
| 64 | + <li key={pet.id}>{pet.name}</li> |
| 65 | + ))} |
| 66 | + </ul> |
| 67 | + </div> |
| 68 | + ); |
| 69 | +} |
| 70 | + |
| 71 | +export default App; |
| 72 | +``` |
| 73 | + |
| 74 | +You can also use pure TS clients. |
| 75 | + |
| 76 | +```tsx |
| 77 | +import { useQuery } from "@tanstack/react-query"; |
| 78 | +import { PetService } from '../openapi/requests/services/PetService'; |
| 79 | +function App() { |
| 80 | + const { data } = useQuery(['MyKey'], () => { |
| 81 | + // Do something here |
| 82 | + |
| 83 | + return PetService.findPetsByStatus(['available']); |
| 84 | + }); |
| 85 | + |
| 86 | + return ( |
| 87 | + <div className="App"> |
| 88 | + {/* .... */} |
| 89 | + </div> |
| 90 | + ); |
| 91 | +} |
| 92 | + |
| 93 | +export default App; |
| 94 | +``` |
| 95 | + |
| 96 | +## License |
| 97 | +MIT |
0 commit comments