├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── __tests__ └── resources │ ├── openapi.json │ └── openapi.yml ├── examples └── cra-example │ ├── .gitignore │ ├── README.md │ ├── openapi.json │ ├── package-lock.json │ ├── package.json │ ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt │ └── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── index.css │ ├── index.js │ ├── logo.svg │ ├── serviceWorker.js │ └── setupTests.js ├── jest.config.js ├── package-lock.json ├── package.json ├── src ├── OpenAPIProvider.test.tsx ├── OpenAPIProvider.tsx ├── index.ts ├── useOperation.test.tsx ├── useOperation.tsx ├── useOperationMethod.test.tsx └── useOperationMethod.tsx └── tsconfig.json /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: anttiviljami 2 | custom: 3 | - https://buymeacoff.ee/anttiviljami 4 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | push: 4 | branches: ["master"] 5 | tags: ["*"] 6 | pull_request: 7 | branches: ["master"] 8 | 9 | jobs: 10 | test: 11 | name: Test 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | - uses: actions/setup-node@v2 16 | - run: npm ci 17 | - run: npm test -- --verbose 18 | 19 | publish: 20 | name: Publish 21 | runs-on: ubuntu-latest 22 | if: startsWith(github.ref, 'refs/tags/') 23 | needs: 24 | - test 25 | steps: 26 | - uses: actions/checkout@v2 27 | - uses: actions/setup-node@v2 28 | with: 29 | registry-url: https://registry.npmjs.org/ 30 | - run: npm ci 31 | - run: npm publish 32 | env: 33 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # build 2 | *.js 3 | *.js.map 4 | *.d.ts 5 | 6 | # include types 7 | !src/types/*.d.ts 8 | 9 | # include jest config 10 | !jest.config.js 11 | 12 | # include example 13 | !examples/*/src/**/*.js 14 | 15 | # npm 16 | node_modules 17 | npm_debug.log* 18 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "typescript", 3 | "arrowParens": "always", 4 | "trailingComma": "all", 5 | "singleQuote": true, 6 | "printWidth": 120 7 | } 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Viljami Kuosmanen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React OpenAPI Client 2 | 3 | [![CI](https://github.com/anttiviljami/react-openapi-client/workflows/CI/badge.svg)](https://github.com/anttiviljami/react-openapi-client/actions?query=workflow%3ACI) 4 | [![npm version](https://img.shields.io/npm/v/react-openapi-client.svg)](https://www.npmjs.com/package/react-openapi-client) 5 | [![bundle size](https://img.shields.io/bundlephobia/minzip/react-openapi-client?label=gzip%20bundle)](https://bundlephobia.com/package/react-openapi-client) 6 | [![License](http://img.shields.io/:license-mit-blue.svg)](https://github.com/anttiviljami/react-openapi-client/blob/master/LICENSE) 7 | [![Buy me a coffee](https://img.shields.io/badge/donate-buy%20me%20a%20coffee-orange)](https://buymeacoff.ee/anttiviljami) 8 | 9 | Consume OpenAPI-enabled APIs with React Hooks 10 | 11 | Uses [`openapi-client-axios`](https://www.npmjs.com/package/openapi-client-axios) under the hood. 12 | 13 | ## Why? 14 | 15 | You can do this: 16 | 17 | ```jsx 18 | import React, { useEffect } from 'react'; 19 | import { useOperation } from 'react-openapi-client'; 20 | 21 | const MyComponent = (props) => { 22 | const { loading, data, error } = useOperation('getPetById', props.id); 23 | // ... 24 | }; 25 | ``` 26 | 27 | Instead of: 28 | 29 | ```jsx 30 | import React, { useEffect, useState } from 'react'; 31 | 32 | const MyComponent = (props) => { 33 | const [loading, setLoading] = useState(false); 34 | const [data, setData] = useState(); 35 | const [error, setError] = useState(); 36 | 37 | useEffect(() => { 38 | (async () => { 39 | setLoading(true); 40 | try { 41 | const res = await fetch(`https://petstore.swagger.io/api/v3/pet/${props.id}`, { 42 | method: 'GET', 43 | headers: { 44 | 'Content-Type': 'application/json', 45 | }, 46 | credentials: 'include', 47 | }); 48 | const data = await res.json(); 49 | setData(data); 50 | } catch (err) { 51 | setError(err); 52 | } 53 | setLoading(false); 54 | })(); 55 | }, [props.id]); 56 | 57 | // ... 58 | }; 59 | ``` 60 | 61 | ## Getting Started 62 | 63 | Install `react-openapi-client` as a dependency 64 | 65 | ``` 66 | npm install --save react-openapi-client axios 67 | ``` 68 | 69 | Wrap your React App with an `OpenAPIProvider`, passing your OpenAPI definition as a prop. 70 | 71 | ```jsx 72 | import React from 'react'; 73 | import { render } from 'react-dom'; 74 | import { OpenAPIProvider } from 'react-openapi-client'; 75 | 76 | const App = () => ( 77 | 78 | 79 | 80 | ); 81 | ``` 82 | 83 | Now you can start using the `useOperation` and `useOperationMethod` hooks in your components. 84 | 85 | ```jsx 86 | import { useOperation } from 'react-openapi-client'; 87 | 88 | const PetDetails = (props) => { 89 | const { loading, data, error } = useOperation('getPetById', props.id); 90 | 91 | if (loading) { 92 | return
Loading...
; 93 | } 94 | 95 | if (error) { 96 | return
Error: {error}
; 97 | } 98 | 99 | return ( 100 |
101 | {data.name} 102 |

{data.name}

103 | 111 |
112 | ); 113 | }; 114 | ``` 115 | 116 | See a full Create-React-App example under [`examples/`](https://github.com/anttiviljami/react-openapi-client/tree/master/examples/) 117 | 118 | ## useOperation hook 119 | 120 | The `useOperation` hook is a great way to declaratively fetch data from your API. 121 | 122 | Important! Calling `useOperation()` always immediately calls the API endpoint. 123 | 124 | Parameters: 125 | 126 | `useOperation` passes the arguments to an OpenAPI Client Axios [`Operation Method`](https://github.com/anttiviljami/openapi-client-axios#operation-methods) 127 | matching the operationId given as the first parameter. 128 | 129 | - [**operationId**](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#fixed-fields-8) (string) Required. the operationId of the operation to call 130 | - [**parameters**](https://github.com/anttiviljami/openapi-client-axios#parameters) (object | string | number) Optional. Parameters for the operation 131 | - [**data**](https://github.com/anttiviljami/openapi-client-axios#data) (object | string | Buffer) Optional. Request payload for the operation 132 | - [**config**](https://github.com/anttiviljami/openapi-client-axios#config-object) (AxiosRequestConfig) Optional. Request payload for the operation 133 | 134 | Return value: 135 | 136 | `useOperation` returns an object containing the following state properties: 137 | 138 | - **loading** (boolean) whether the API request is currently ongoing. 139 | - **data** (any) the parsed response data for the operation. 140 | - **response** (any) the raw axios response object for the operation. 141 | - **error** (Error) contains an error object, in case the request fails 142 | - **api** (OpenAPIClientAxios) reference to the API client class instance 143 | 144 | Example usage: 145 | 146 | ```javascript 147 | const { loading, data, error } = useOperation('getPetById', 1, null, { headers: { 'x-api-key': 'secret' } }); 148 | ``` 149 | 150 | ## useOperationMethod hook 151 | 152 | The `useOperationMethod` hook can be used to obtain a callable operation method. 153 | 154 | Unlike `useOperation`, calling `useOperationMethod()` has no side effects. 155 | 156 | Parameters: 157 | 158 | `useOperationMethod` gets the corresponding OpenAPI Client Axios [`Operation Method`](https://github.com/anttiviljami/openapi-client-axios#operation-methods) 159 | matching the operationId. 160 | 161 | - [**operationId**](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#fixed-fields-8) (string) Required. the operationId of the operation to call 162 | 163 | Return value: 164 | 165 | `useOperationMethod` returns a tuple (javascript array), where the first 166 | element is the callable operation method, and the second method contains the 167 | same object as `useOperation`'s return value. 168 | 169 | See [OpenAPI Client Axios documentation](https://github.com/anttiviljami/openapi-client-axios/blob/master/DOCS.md#operation-method) 170 | for more details on how to use the Operation Methods. 171 | 172 | Example usage: 173 | 174 | ```javascript 175 | const [createPet, { loading, response, error }] = useOperationMethod('createPet'); 176 | ``` 177 | 178 | ## OpenAPIProvider 179 | 180 | The `OpenAPIProvider` component provides `OpenAPIContext` to all nested components in the 181 | React DOM so they can use the `useOperation` and `useOperationMethod` hooks. 182 | 183 | Internally, the Provider instantiates an instance of OpenAPIClientAxios, which 184 | is then used by the hooks to call the API operations. 185 | 186 | In addition to the definition file, you can pass any [constructor options](https://github.com/anttiviljami/openapi-client-axios/blob/master/DOCS.md#class-openapiclientaxios) 187 | accepted by OpenAPIClientAxios as props to the `OpenAPIProvider` component. 188 | 189 | Example usage: 190 | 191 | ```jsx 192 | const App = () => ( 193 | 194 | 195 | 196 | ) 197 | ``` 198 | 199 | You can also access the `OpenAPIClientAxios` instance by using the React `useContext` hook: 200 | 201 | ```jsx 202 | import React, { useContext } from 'react'; 203 | import { OpenAPIContext } from 'react-openapi-client'; 204 | 205 | const MyComponent = () => { 206 | const { api } = useContext(OpenAPIContext); 207 | const client = api.client; 208 | const definition = api.definition; 209 | // ... 210 | } 211 | ``` 212 | 213 | ## Contributing 214 | 215 | React OpenAPI Client is Free and Open Source Software. Issues and pull requests are more than welcome! 216 | 217 | [The Chilicorn](https://spiceprogram.org/oss-sponsorship) 218 | -------------------------------------------------------------------------------- /__tests__/resources/openapi.json: -------------------------------------------------------------------------------- 1 | { 2 | "openapi": "3.0.1", 3 | "info": { 4 | "title": "My API", 5 | "version": "1.0.0" 6 | }, 7 | "paths": { 8 | "/pets": { 9 | "get": { 10 | "operationId": "getPets", 11 | "responses": { 12 | "200": { 13 | "$ref": "#/components/responses/ListPetsRes" 14 | } 15 | } 16 | }, 17 | "post": { 18 | "operationId": "createPet", 19 | "requestBody": { 20 | "description": "Pet object to create", 21 | "content": { 22 | "application/json": {} 23 | } 24 | }, 25 | "responses": { 26 | "201": { 27 | "$ref": "#/components/responses/PetRes" 28 | } 29 | } 30 | } 31 | }, 32 | "/pets/{id}": { 33 | "get": { 34 | "operationId": "getPetById", 35 | "responses": { 36 | "200": { 37 | "$ref": "#/components/responses/PetRes" 38 | } 39 | }, 40 | "parameters": [ 41 | { 42 | "name": "id", 43 | "in": "path", 44 | "required": true, 45 | "schema": { 46 | "type": "integer" 47 | } 48 | } 49 | ] 50 | } 51 | } 52 | }, 53 | "components": { 54 | "schemas": { 55 | "Pet": { 56 | "type": "object", 57 | "properties": { 58 | "id": { 59 | "type": "integer", 60 | "minimum": 1 61 | }, 62 | "name": { 63 | "type": "string", 64 | "example": "Odie" 65 | } 66 | } 67 | } 68 | }, 69 | "responses": { 70 | "ListPetsRes": { 71 | "description": "ok", 72 | "content": { 73 | "application/json": { 74 | "schema": { 75 | "type": "array", 76 | "items": { 77 | "$ref": "#/components/schemas/Pet" 78 | } 79 | } 80 | } 81 | } 82 | }, 83 | "PetRes": { 84 | "description": "ok", 85 | "content": { 86 | "application/json": { 87 | "schema": { 88 | "$ref": "#/components/schemas/Pet" 89 | } 90 | } 91 | } 92 | } 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /__tests__/resources/openapi.yml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.1 2 | info: 3 | title: My API 4 | version: 1.0.0 5 | paths: 6 | /pets: 7 | get: 8 | operationId: getPets 9 | responses: 10 | '200': 11 | $ref: '#/components/responses/ListPetsRes' 12 | post: 13 | operationId: createPet 14 | requestBody: 15 | description: Pet object to create 16 | content: 17 | application/json: {} 18 | responses: 19 | '201': 20 | $ref: '#/components/responses/PetRes' 21 | '/pets/{id}': 22 | get: 23 | operationId: getPetById 24 | responses: 25 | '200': 26 | $ref: '#/components/responses/PetRes' 27 | parameters: 28 | - name: id 29 | in: path 30 | required: true 31 | schema: 32 | type: integer 33 | components: 34 | schemas: 35 | Pet: 36 | type: object 37 | properties: 38 | id: 39 | type: integer 40 | minimum: 1 41 | name: 42 | type: string 43 | example: Odie 44 | responses: 45 | ListPetsRes: 46 | description: ok 47 | content: 48 | application/json: 49 | schema: 50 | type: array 51 | items: 52 | $ref: '#/components/schemas/Pet' 53 | PetRes: 54 | description: ok 55 | content: 56 | application/json: 57 | schema: 58 | $ref: '#/components/schemas/Pet' 59 | -------------------------------------------------------------------------------- /examples/cra-example/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /examples/cra-example/README.md: -------------------------------------------------------------------------------- 1 | # react-openapi-client-cra-example 2 | 3 | Create-React-App Example using `react-openapi-client` 4 | 5 | ## How to run: 6 | 7 | ``` 8 | npm install 9 | npm run dev 10 | ``` 11 | 12 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 13 | 14 | ## Available Scripts 15 | 16 | In the project directory, you can run: 17 | 18 | ### `npm start` 19 | 20 | Runs the app in the development mode.
21 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 22 | 23 | The page will reload if you make edits.
24 | You will also see any lint errors in the console. 25 | 26 | ### `npm test` 27 | 28 | Launches the test runner in the interactive watch mode.
29 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 30 | 31 | ### `npm run build` 32 | 33 | Builds the app for production to the `build` folder.
34 | It correctly bundles React in production mode and optimizes the build for the best performance. 35 | 36 | The build is minified and the filenames include the hashes.
37 | Your app is ready to be deployed! 38 | 39 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 40 | 41 | ## Learn More 42 | 43 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 44 | 45 | To learn React, check out the [React documentation](https://reactjs.org/). 46 | 47 | ### Code Splitting 48 | 49 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 50 | 51 | ### Analyzing the Bundle Size 52 | 53 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 54 | 55 | ### Making a Progressive Web App 56 | 57 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 58 | 59 | ### Advanced Configuration 60 | 61 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 62 | 63 | ### Deployment 64 | 65 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 66 | 67 | ### `npm run build` fails to minify 68 | 69 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 70 | -------------------------------------------------------------------------------- /examples/cra-example/openapi.json: -------------------------------------------------------------------------------- 1 | { 2 | "openapi": "3.0.1", 3 | "info": { 4 | "title": "My API", 5 | "version": "1.0.0" 6 | }, 7 | "paths": { 8 | "/pets": { 9 | "get": { 10 | "operationId": "listPets", 11 | "responses": { 12 | "200": { 13 | "$ref": "#/components/responses/ListPetsRes" 14 | } 15 | } 16 | } 17 | }, 18 | "/pets/{id}": { 19 | "get": { 20 | "operationId": "getPetById", 21 | "responses": { 22 | "200": { 23 | "$ref": "#/components/responses/PetRes" 24 | } 25 | }, 26 | "parameters": [ 27 | { 28 | "name": "id", 29 | "in": "path", 30 | "required": true, 31 | "schema": { 32 | "type": "integer" 33 | } 34 | } 35 | ] 36 | }, 37 | "post": { 38 | "operationId": "deletePetById", 39 | "responses": { 40 | "204": { 41 | "description": "deleted successfully" 42 | } 43 | }, 44 | "parameters": [ 45 | { 46 | "name": "id", 47 | "in": "path", 48 | "required": true, 49 | "schema": { 50 | "type": "integer" 51 | } 52 | } 53 | ] 54 | } 55 | } 56 | }, 57 | "components": { 58 | "schemas": { 59 | "Pet": { 60 | "type": "object", 61 | "properties": { 62 | "id": { 63 | "type": "integer", 64 | "minimum": 1 65 | }, 66 | "name": { 67 | "type": "string", 68 | "example": "Odie" 69 | }, 70 | "status": { 71 | "type": "string", 72 | "enum": [ 73 | "AVAILABLE", 74 | "NOT_AVAILABLE" 75 | ] 76 | }, 77 | "image": { 78 | "type": "string", 79 | "format": "uri", 80 | "example": "https://vignette.wikia.nocookie.net/garfield/images/a/ac/OdieCharacter.jpg/revision/latest/top-crop/width/360/height/450" 81 | } 82 | } 83 | } 84 | }, 85 | "responses": { 86 | "ListPetsRes": { 87 | "description": "ok", 88 | "content": { 89 | "application/json": { 90 | "schema": { 91 | "type": "array", 92 | "items": { 93 | "$ref": "#/components/schemas/Pet" 94 | } 95 | } 96 | } 97 | } 98 | }, 99 | "PetRes": { 100 | "description": "ok", 101 | "content": { 102 | "application/json": { 103 | "schema": { 104 | "$ref": "#/components/schemas/Pet" 105 | } 106 | } 107 | } 108 | } 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /examples/cra-example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-openapi-client-cra-example", 3 | "version": "0.2.0", 4 | "private": true, 5 | "dependencies": { 6 | "axios": "^0.24.0", 7 | "react": "^17.0.2", 8 | "react-dom": "^17.0.2", 9 | "react-openapi-client": "^0.2.0" 10 | }, 11 | "scripts": { 12 | "dev": "concurrently npm:start npm:mock", 13 | "start": "SKIP_PREFLIGHT_CHECK=true react-scripts start", 14 | "build": "react-scripts build", 15 | "test": "react-scripts test", 16 | "mock": "openapi mock openapi.json -p 5001", 17 | "link": "rm -fr ../../node_modules/react && npm link ../../ && npm link ../../node_modules/react" 18 | }, 19 | "eslintConfig": { 20 | "extends": "react-app" 21 | }, 22 | "browserslist": { 23 | "production": [ 24 | ">0.2%", 25 | "not dead", 26 | "not op_mini all" 27 | ], 28 | "development": [ 29 | "last 1 chrome version", 30 | "last 1 firefox version", 31 | "last 1 safari version" 32 | ] 33 | }, 34 | "devDependencies": { 35 | "@testing-library/jest-dom": "^5.16.1", 36 | "@testing-library/react": "^12.1.2", 37 | "@testing-library/user-event": "^13.5.0", 38 | "concurrently": "^5.1.0", 39 | "openapicmd": "^1.8.2", 40 | "react-scripts": "^4.0.3" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/cra-example/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anttiviljami/react-openapi-client/18593db12618e4024a6b8432d72ba8ef2074cd3c/examples/cra-example/public/favicon.ico -------------------------------------------------------------------------------- /examples/cra-example/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /examples/cra-example/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anttiviljami/react-openapi-client/18593db12618e4024a6b8432d72ba8ef2074cd3c/examples/cra-example/public/logo192.png -------------------------------------------------------------------------------- /examples/cra-example/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anttiviljami/react-openapi-client/18593db12618e4024a6b8432d72ba8ef2074cd3c/examples/cra-example/public/logo512.png -------------------------------------------------------------------------------- /examples/cra-example/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /examples/cra-example/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /examples/cra-example/src/App.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anttiviljami/react-openapi-client/18593db12618e4024a6b8432d72ba8ef2074cd3c/examples/cra-example/src/App.css -------------------------------------------------------------------------------- /examples/cra-example/src/App.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useOperation, useOperationMethod, OpenAPIProvider } from 'react-openapi-client'; 3 | 4 | const App = () => ( 5 | 6 | 7 | 8 | ); 9 | 10 | const PetDetails = (props) => { 11 | // useOperation is called right away as an effect 12 | const { loading, error, data } = useOperation('getPetById', props.id); 13 | 14 | // useOperationMethod returns a method you can call 15 | const [deletePetById, deleteState] = useOperationMethod('deletePetById'); 16 | 17 | if (loading || !data) { 18 | return
Loading...
; 19 | } 20 | 21 | if (error) { 22 | return
Error: {error}
; 23 | } 24 | 25 | return ( 26 |
27 | {data.name} 28 |

{data.name}

29 | 37 | 40 | {deleteState.response &&

Success!

} 41 | {deleteState.error &&

Error deleting pet: {deleteState.error}

} 42 |
43 | ); 44 | }; 45 | 46 | export default App; 47 | -------------------------------------------------------------------------------- /examples/cra-example/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from '@testing-library/react'; 3 | import App from './App'; 4 | 5 | test('renders learn react link', () => { 6 | const { getByText } = render(); 7 | const linkElement = getByText(/learn react/i); 8 | expect(linkElement).toBeInTheDocument(); 9 | }); 10 | -------------------------------------------------------------------------------- /examples/cra-example/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /examples/cra-example/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render( 8 | 9 | 10 | , 11 | document.getElementById('root'), 12 | ); 13 | 14 | // If you want your app to work offline and load faster, you can change 15 | // unregister() to register() below. Note this comes with some pitfalls. 16 | // Learn more about service workers: https://bit.ly/CRA-PWA 17 | serviceWorker.unregister(); 18 | -------------------------------------------------------------------------------- /examples/cra-example/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /examples/cra-example/src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' }, 105 | }) 106 | .then(response => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then(registration => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready 134 | .then(registration => { 135 | registration.unregister(); 136 | }) 137 | .catch(error => { 138 | console.error(error.message); 139 | }); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /examples/cra-example/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest', 3 | testEnvironment: 'jsdom', 4 | testMatch: ['**/?(*.)+(spec|test).ts?(x)'], 5 | }; 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-openapi-client", 3 | "description": "Consume OpenAPI-enabled APIs with React Hooks", 4 | "version": "0.2.2", 5 | "author": "Viljami Kuosmanen ", 6 | "license": "MIT", 7 | "keywords": [ 8 | "react", 9 | "useOperation", 10 | "openapi", 11 | "swagger", 12 | "client", 13 | "axios", 14 | "frontend", 15 | "browser", 16 | "typescript" 17 | ], 18 | "homepage": "https://github.com/anttiviljami/react-openapi-client", 19 | "repository": { 20 | "type": "git", 21 | "url": "git+https://github.com/anttiviljami/react-openapi-client.git" 22 | }, 23 | "bugs": { 24 | "url": "https://github.com/anttiviljami/react-openapi-client/issues" 25 | }, 26 | "main": "index.js", 27 | "types": "index.d.ts", 28 | "files": [ 29 | "*.js", 30 | "*.d.ts", 31 | "**/*.js", 32 | "**/*.d.ts", 33 | "!*.test.*", 34 | "!**/*.test.*", 35 | "!node_modules", 36 | "!src", 37 | "!*.config.js" 38 | ], 39 | "peerDependencies": { 40 | "react": "^17.0.2", 41 | "react-dom": "^17.0.2", 42 | "axios": "^0.24.0" 43 | }, 44 | "dependencies": { 45 | "openapi-client-axios": "^4.4.9" 46 | }, 47 | "devDependencies": { 48 | "@testing-library/jest-dom": "^5.16.1", 49 | "@testing-library/react": "^12.1.2", 50 | "@testing-library/react-hooks": "^7.0.2", 51 | "@types/jest": "^25.1.4", 52 | "@types/node": "^13.9.8", 53 | "@types/react": "^16.9.30", 54 | "@types/react-dom": "^16.9.5", 55 | "axios": "^0.24.0", 56 | "isomorphic-fetch": "^2.2.1", 57 | "jest": "^27.4.4", 58 | "js-yaml": "^4.1.0", 59 | "react": "^17.0.2", 60 | "react-dom": "^17.0.2", 61 | "react-test-renderer": "^17.0.2", 62 | "ts-jest": "^27.1.1", 63 | "typescript": "^4.5.3" 64 | }, 65 | "scripts": { 66 | "build": "tsc", 67 | "watch-build": "tsc -w", 68 | "prettier": "prettier --write src/** __tests__/**", 69 | "prepare": "npm run build", 70 | "test": "NODE_ENV=test jest" 71 | } 72 | } -------------------------------------------------------------------------------- /src/OpenAPIProvider.test.tsx: -------------------------------------------------------------------------------- 1 | import React, { FunctionComponent, useContext } from 'react'; 2 | import fs from 'fs'; 3 | import path from 'path'; 4 | import { OpenAPIProvider, OpenAPIContext } from '.'; 5 | import { render } from '@testing-library/react'; 6 | import '@testing-library/jest-dom/extend-expect'; 7 | import OpenAPIClientAxios from 'openapi-client-axios'; 8 | 9 | jest.mock('openapi-client-axios'); 10 | 11 | const definition = JSON.parse( 12 | fs.readFileSync(path.join(__dirname, '..', '__tests__', 'resources', 'openapi.json')).toString(), 13 | ); 14 | 15 | describe('OpenAPIProvider', () => { 16 | it('can be used as a component', () => { 17 | // given 18 | const props = { definition }; 19 | 20 | // when 21 | const result = render(); 22 | 23 | // then 24 | expect(result.container).toBeInTheDocument(); 25 | }); 26 | 27 | it('provides OpenAPIContext with reference to api to child components', () => { 28 | // given 29 | const props = { definition }; 30 | let providedContext: { api: OpenAPIClientAxios }; 31 | const TestComponent: FunctionComponent = jest.fn(() => { 32 | providedContext = useContext(OpenAPIContext); 33 | return <>; 34 | }); 35 | const renderFunction = TestComponent as jest.Mock; 36 | 37 | // when 38 | render( 39 | 40 | 41 | , 42 | ); 43 | 44 | // then 45 | expect(renderFunction).toBeCalled(); 46 | expect(providedContext).toHaveProperty('api'); 47 | expect(providedContext.api).toBeInstanceOf(OpenAPIClientAxios); 48 | }); 49 | 50 | it('passes props as parameters to OpenAPIClientAxios constructor', () => { 51 | // given 52 | const props = { definition, strict: true, validate: true, axiosConfigDefaults: { withCredentials: true } }; 53 | 54 | // when 55 | render(); 56 | 57 | // then 58 | expect(OpenAPIClientAxios).toHaveBeenCalledWith(props); 59 | }); 60 | }); 61 | -------------------------------------------------------------------------------- /src/OpenAPIProvider.tsx: -------------------------------------------------------------------------------- 1 | import React, { createContext, ReactNode, useMemo } from 'react'; 2 | import OpenAPIClientAxios from 'openapi-client-axios'; 3 | 4 | export const OpenAPIContext: React.Context<{ 5 | api: OpenAPIClientAxios; 6 | }> = createContext({ api: undefined }); 7 | 8 | type OpenAPIClientAxiosOpts = ConstructorParameters[0]; 9 | 10 | interface Props extends OpenAPIClientAxiosOpts { 11 | children?: ReactNode; 12 | } 13 | 14 | export const OpenAPIProvider = ({ children, ...clientOpts }: Props) => { 15 | const api = useMemo(() => new OpenAPIClientAxios({ ...clientOpts }), [clientOpts]); 16 | try { 17 | api.initSync(); 18 | } catch (err) {} 19 | return {children}; 20 | }; 21 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './OpenAPIProvider'; 2 | export * from './useOperationMethod'; 3 | export * from './useOperation'; 4 | -------------------------------------------------------------------------------- /src/useOperation.test.tsx: -------------------------------------------------------------------------------- 1 | import React, { ReactNode } from 'react'; 2 | import fs from 'fs'; 3 | import path from 'path'; 4 | import { useOperation, OpenAPIProvider } from '.'; 5 | import { renderHook, act } from '@testing-library/react-hooks'; 6 | 7 | const definition = JSON.parse( 8 | fs.readFileSync(path.join(__dirname, '..', '__tests__', 'resources', 'openapi.json')).toString(), 9 | ); 10 | 11 | describe('useOperation', () => { 12 | const wrapper = ({ children }: { children?: ReactNode }) => ( 13 | {children} 14 | ); 15 | 16 | it('should call the api operation method', async () => { 17 | // given 18 | const { result, waitForValueToChange } = renderHook(() => useOperation('getPets'), { wrapper }); 19 | const mock = jest.spyOn(result.current.api.client, 'getPets').mockImplementationOnce(async () => null); 20 | 21 | // when 22 | await act(() => waitForValueToChange(() => result.current.loading)); 23 | 24 | // then 25 | expect(mock).toBeCalled(); 26 | }); 27 | 28 | it('should set loading initially to true', async () => { 29 | // given 30 | const { result, waitForValueToChange } = renderHook(() => useOperation('getPets'), { wrapper }); 31 | jest.spyOn(result.current.api.client, 'getPets').mockImplementationOnce(async () => null); 32 | 33 | // when 34 | expect(result.current.loading).toBe(true); 35 | 36 | // then 37 | await act(() => waitForValueToChange(() => result.current.loading)); 38 | }); 39 | 40 | describe('success response', () => { 41 | it('should set response object', async () => { 42 | // given 43 | const { result, waitForNextUpdate } = renderHook(() => useOperation('getPets'), { wrapper }); 44 | jest.spyOn(result.current.api.client, 'getPets').mockImplementationOnce(() => ({ status: 200, data: {} } as any)); 45 | 46 | // when 47 | await act(() => waitForNextUpdate()); 48 | 49 | // then 50 | expect(result.current.response).toBeTruthy(); 51 | }); 52 | 53 | it('should set data from response', async () => { 54 | // given 55 | const expected = { example: 1 }; 56 | const { result, waitForNextUpdate } = renderHook(() => useOperation('getPets'), { wrapper }); 57 | jest 58 | .spyOn(result.current.api.client, 'getPets') 59 | .mockImplementationOnce(() => ({ status: 200, data: expected } as any)); 60 | 61 | // when 62 | await act(() => waitForNextUpdate()); 63 | 64 | // then 65 | expect(result.current.data).toBe(expected); 66 | }); 67 | 68 | it('should set loading to false after endpoint returns', async () => { 69 | // given 70 | const { result, waitForNextUpdate } = renderHook(() => useOperation('getPets'), { wrapper }); 71 | jest 72 | .spyOn(result.current.api.client, 'getPets') 73 | .mockImplementationOnce(() => ({ status: 200, data: null } as any)); 74 | 75 | // when 76 | await act(() => waitForNextUpdate()); 77 | 78 | // then 79 | expect(result.current.loading).toBe(false); 80 | }); 81 | 82 | it('error should be falsy', async () => { 83 | // given 84 | const { result, waitForNextUpdate } = renderHook(() => useOperation('getPets'), { wrapper }); 85 | jest 86 | .spyOn(result.current.api.client, 'getPets') 87 | .mockImplementationOnce(() => ({ status: 200, data: null } as any)); 88 | 89 | // when 90 | await act(() => waitForNextUpdate()); 91 | 92 | // then 93 | expect(result.current.error).toBeFalsy(); 94 | }); 95 | }); 96 | 97 | describe('error response', () => { 98 | it('should not set data from response', async () => { 99 | // given 100 | const { result, waitForNextUpdate } = renderHook(() => useOperation('getPets'), { wrapper }); 101 | jest.spyOn(result.current.api.client, 'getPets').mockImplementationOnce(() => { 102 | throw new Error(); 103 | }); 104 | 105 | // when 106 | await act(() => waitForNextUpdate()); 107 | 108 | // then 109 | expect(result.current.data).toBe(undefined); 110 | }); 111 | 112 | it('should set loading to false after endpoint returns', async () => { 113 | // given 114 | const { result, waitForNextUpdate } = renderHook(() => useOperation('getPets'), { wrapper }); 115 | jest.spyOn(result.current.api.client, 'getPets').mockImplementationOnce(() => { 116 | throw new Error(); 117 | }); 118 | 119 | // when 120 | await act(() => waitForNextUpdate()); 121 | 122 | // then 123 | expect(result.current.loading).toBe(false); 124 | }); 125 | 126 | it('error should contain the thrown error', async () => { 127 | // given 128 | const expected = new Error(); 129 | const { result, waitForNextUpdate } = renderHook(() => useOperation('getPets'), { wrapper }); 130 | jest.spyOn(result.current.api.client, 'getPets').mockImplementationOnce(() => { 131 | throw expected; 132 | }); 133 | 134 | // when 135 | await act(() => waitForNextUpdate()); 136 | 137 | // then 138 | expect(result.current.error).toBe(expected); 139 | }); 140 | }); 141 | }); 142 | -------------------------------------------------------------------------------- /src/useOperation.tsx: -------------------------------------------------------------------------------- 1 | import { useContext, useState, useEffect } from 'react'; 2 | import { OpenAPIContext } from './OpenAPIProvider'; 3 | import { AxiosResponse, OpenAPIClientAxios, UnknownOperationMethod, AxiosError } from 'openapi-client-axios'; 4 | 5 | type OperationParameters = Parameters; 6 | 7 | export function useOperation( 8 | operationId: string, 9 | ...params: OperationParameters 10 | ): { loading: boolean; error?: Error; data?: any; response: AxiosResponse; api: OpenAPIClientAxios } { 11 | const { api } = useContext(OpenAPIContext); 12 | 13 | const [loading, setLoading] = useState(true); 14 | const [error, setError] = useState(undefined); 15 | const [data, setData] = useState(undefined); 16 | const [response, setResponse] = useState(undefined); 17 | 18 | useEffect(() => { 19 | (async () => { 20 | const client = await api.getClient(); 21 | let res: AxiosResponse; 22 | try { 23 | res = await client[operationId](...params); 24 | setResponse(res); 25 | setData(res.data); 26 | } catch (err) { 27 | setError(err as AxiosError); 28 | } 29 | setLoading(false); 30 | })(); 31 | }, [api]); 32 | 33 | return { loading, error, data, response, api }; 34 | } 35 | -------------------------------------------------------------------------------- /src/useOperationMethod.test.tsx: -------------------------------------------------------------------------------- 1 | import React, { ReactNode } from 'react'; 2 | import fs from 'fs'; 3 | import path from 'path'; 4 | import { useOperationMethod, OpenAPIProvider } from '.'; 5 | import { renderHook, act } from '@testing-library/react-hooks'; 6 | 7 | const definition = JSON.parse( 8 | fs.readFileSync(path.join(__dirname, '..', '__tests__', 'resources', 'openapi.json')).toString(), 9 | ); 10 | 11 | describe('useOperationMethod', () => { 12 | const wrapper = ({ children }: { children?: ReactNode }) => ( 13 | {children} 14 | ); 15 | 16 | it('should return a method that calls the api operation method', async () => { 17 | // given 18 | const { result } = renderHook(() => useOperationMethod('getPets'), { wrapper }); 19 | const [getPets, { api }] = result.current; 20 | const mock = jest.spyOn(api.client, 'getPets').mockImplementationOnce(() => null); 21 | 22 | // when 23 | await act(() => getPets()); 24 | 25 | // then 26 | expect(mock).toBeCalled(); 27 | }); 28 | 29 | it('should set loading initially to false', async () => { 30 | // given 31 | const { result } = renderHook(() => useOperationMethod('getPets'), { wrapper }); 32 | const [, { loading }] = result.current; 33 | 34 | // then 35 | expect(loading).toBe(false); 36 | }); 37 | 38 | it('should set loading to true after calling the operation method', async () => { 39 | // given 40 | const { result, waitForValueToChange } = renderHook(() => useOperationMethod('getPets'), { wrapper }); 41 | const [getPets, { api }] = result.current; 42 | jest.spyOn(api.client, 'getPets').mockImplementationOnce(() => null); 43 | 44 | // when 45 | act(() => { 46 | getPets(); 47 | }); 48 | 49 | // then 50 | expect(result.current[1].loading).toBe(true); 51 | await act(() => waitForValueToChange(() => result.current[1].loading)); 52 | }); 53 | 54 | describe('success response', () => { 55 | beforeAll(() => { 56 | jest.useFakeTimers(); 57 | }); 58 | 59 | it('should set response object', async () => { 60 | // given 61 | const { result } = renderHook(() => useOperationMethod('getPets'), { wrapper }); 62 | const [getPets, { api }] = result.current; 63 | jest.spyOn(api.client, 'getPets').mockImplementationOnce(() => ({ status: 200, data: {} } as any)); 64 | 65 | // when 66 | await act(() => getPets()); 67 | 68 | // then 69 | expect(result.current[1].response.status).toBe(200); 70 | }); 71 | 72 | it('should set data from response', async () => { 73 | // given 74 | const expected = { example: 1 }; 75 | const { result } = renderHook(() => useOperationMethod('getPets'), { wrapper }); 76 | const [getPets, { api }] = result.current; 77 | jest.spyOn(api.client, 'getPets').mockImplementationOnce(() => ({ status: 200, data: expected } as any)); 78 | 79 | // when 80 | await act(() => getPets()); 81 | 82 | // then 83 | expect(result.current[1].data).toBe(expected); 84 | }); 85 | 86 | it('should set loading to false after endpoint returns', async () => { 87 | // given 88 | const { result } = renderHook(() => useOperationMethod('getPets'), { wrapper }); 89 | const [getPets, { api }] = result.current; 90 | jest.spyOn(api.client, 'getPets').mockImplementationOnce(() => ({ status: 200, data: null } as any)); 91 | 92 | // when 93 | await act(() => getPets()); 94 | 95 | // then 96 | expect(result.current[1].loading).toBe(false); 97 | }); 98 | 99 | it('error should be falsy', async () => { 100 | // given 101 | const { result } = renderHook(() => useOperationMethod('getPets'), { wrapper }); 102 | const [getPets, { api }] = result.current; 103 | jest.spyOn(api.client, 'getPets').mockImplementationOnce(() => ({ status: 200, data: null } as any)); 104 | 105 | // when 106 | await act(() => getPets()); 107 | 108 | // then 109 | expect(result.current[1].error).toBeFalsy(); 110 | }); 111 | }); 112 | 113 | describe('error response', () => { 114 | it('should not set data from response', async () => { 115 | // given 116 | const { result } = renderHook(() => useOperationMethod('getPets'), { wrapper }); 117 | const [getPets, { api }] = result.current; 118 | jest.spyOn(api.client, 'getPets').mockImplementationOnce(() => { 119 | throw new Error(); 120 | }); 121 | 122 | // when 123 | await act(() => getPets()); 124 | 125 | // then 126 | expect(result.current[1].data).toBe(undefined); 127 | }); 128 | 129 | it('should set loading to false after endpoint returns', async () => { 130 | // given 131 | const { result } = renderHook(() => useOperationMethod('getPets'), { wrapper }); 132 | const [getPets, { api }] = result.current; 133 | jest.spyOn(api.client, 'getPets').mockImplementationOnce(() => { 134 | throw new Error(); 135 | }); 136 | 137 | // when 138 | await act(() => getPets()); 139 | 140 | // then 141 | expect(result.current[1].loading).toBe(false); 142 | }); 143 | 144 | it('error should contain the thrown error', async () => { 145 | // given 146 | const expected = new Error(); 147 | const { result } = renderHook(() => useOperationMethod('getPets'), { wrapper }); 148 | const [getPets, { api }] = result.current; 149 | jest.spyOn(api.client, 'getPets').mockImplementationOnce(() => { 150 | throw expected; 151 | }); 152 | 153 | // when 154 | await act(() => getPets()); 155 | 156 | // then 157 | expect(result.current[1].error).toBe(expected); 158 | }); 159 | }); 160 | }); 161 | -------------------------------------------------------------------------------- /src/useOperationMethod.tsx: -------------------------------------------------------------------------------- 1 | import { useContext, useState, useCallback } from 'react'; 2 | import { OpenAPIContext } from './OpenAPIProvider'; 3 | import { UnknownOperationMethod, OpenAPIClientAxios, AxiosResponse, AxiosError } from 'openapi-client-axios'; 4 | 5 | export function useOperationMethod( 6 | operationId: string, 7 | ): [ 8 | UnknownOperationMethod, 9 | { loading: boolean; error?: Error; data?: any; response: AxiosResponse; api: OpenAPIClientAxios }, 10 | ] { 11 | const { api } = useContext(OpenAPIContext); 12 | 13 | const [loading, setLoading] = useState(false); 14 | const [error, setError] = useState(undefined); 15 | const [data, setData] = useState(undefined); 16 | const [response, setResponse] = useState(undefined); 17 | 18 | const operationMethod: UnknownOperationMethod = useCallback( 19 | async (...params) => { 20 | setLoading(true); 21 | const client = await api.getClient(); 22 | let res: AxiosResponse; 23 | try { 24 | res = await client[operationId](...params); 25 | setResponse(res); 26 | setData(res.data); 27 | } catch (err) { 28 | setError(err as AxiosError); 29 | } 30 | setLoading(false); 31 | return res; 32 | }, 33 | [setLoading, setData, setError, api], 34 | ); 35 | 36 | return [operationMethod, { loading, error, data, response, api }]; 37 | } 38 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowSyntheticDefaultImports": true, 4 | "strict": true, 5 | "target": "es5", 6 | "module": "commonjs", 7 | "moduleResolution": "node", 8 | "lib": [ 9 | "dom", 10 | "esnext" 11 | ], 12 | "jsx": "react", 13 | "experimentalDecorators": true, 14 | "emitDecoratorMetadata": true, 15 | "esModuleInterop": true, 16 | "noImplicitAny": true, 17 | "strictPropertyInitialization": false, 18 | "strictNullChecks": false, 19 | "baseUrl": ".", 20 | "rootDir": "src", 21 | "outDir": "", 22 | "sourceMap": true, 23 | "declaration": true 24 | }, 25 | "include": [ 26 | "src/**/*" 27 | ] 28 | } 29 | --------------------------------------------------------------------------------