Node.js library that generates React Query (also called TanStack Query) hooks based on an OpenAPI specification file.
- Supports generation of custom react hooks that use React Query's
useQueryanduseMutationhooks - Supports generation of query keys for query caching
- Supports the option to use pure TypeScript clients generated by OpenAPI Typescript Codegen
$ 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$ 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") --useUnionTypes Use union types (default: false) --exportSchemas <value> Write schemas to disk (default: false) --indent <value> Indentation options [4, 2, tabs] (default: "4") --postfixServices <value> Service name postfix (default: "Service") --postfixModels <value> Modal name postfix --request <value> Path to custom request file -h, --help display help for command $ openapi-rq -i ./petstore.yaml - openapi - queries - index.ts <- custom react hooks - requests <- output code generated by OpenAPI Typescript Codegen // App.tsximport{usePetServiceFindPetsByStatus,}from"../openapi/queries";functionApp(){const{ data }=usePetServiceFindPetsByStatus({status: ["available"]});return(<divclassName="App"><h1>Pet List</h1><ul>{data?.map((pet)=>(<likey={pet.id}>{pet.name}</li>))}</ul></div>);}exportdefaultApp;You can also use pure TS clients.
import{useQuery}from"@tanstack/react-query";import{PetService}from'../openapi/requests/services/PetService';import{usePetServiceFindPetsByStatusKey,}from"../openapi/queries";functionApp(){// You can still use the auto-generated query keyconst{ data }=useQuery({queryKey: [usePetServiceFindPetsByStatusKey],queryFn: ()=>{// Do something herereturnPetService.findPetsByStatus(['available']);}});return(<divclassName="App">{/* .... */}</div>);}exportdefaultApp;MIT