Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(query): allow body type customisation through mutator for mutations #319

Merged
merged 5 commits into from
Mar 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/src/pages/guides/custom-axios.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,7 @@ export const customInstance = <T>(config: AxiosRequestConfig): Promise<T> => {

// In some case with react-query and swr you want to be able to override the return error type so you can also do it here like this
export type ErrorType<Error> = AxiosError<Error>;
// In case you want to wrap the body type (optional)
// (if the custom instance is processing data before sending it, like changing the case for example)
export type BodyType<BodyData> = CamelCase<BodyType>
```
7 changes: 5 additions & 2 deletions docs/src/pages/guides/custom-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const customInstance = async <T>({
url: string;
method: 'get' | 'post' | 'put' | 'delete' | 'patch';
params?: any;
data?: any;
data?: BodyType<unknown>;
responseType?: string;
}): Promise<T> => {
const response = await fetch(
Expand All @@ -51,4 +51,7 @@ export default customInstance;

// In some case with react-query and swr you want to be able to override the return error type so you can also do it here like this
export type ErrorType<Error> = AxiosError<Error>;
```
// In case you want to wrap the body type (optional)
// (if the custom instance is processing data before sending it, like changing the case for example)
export type BodyType<BodyData> = CamelCase<BodyType>
```
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ export const getListPetsKey = (params?: ListPetsParams,
version= 1,) => [`/v${version}/pets`, ...(params ? [params]: [])];


export type ListPetsQueryResult = NonNullable<AsyncReturnType<typeof listPets>>
export type ListPetsQueryError = Error
export type ListPetsQueryResult = NonNullable<AsyncReturnType<typeof listPets>>
export type ListPetsQueryError = Error

export const useListPets = <TError = Error>(
params?: ListPetsParams,
Expand Down Expand Up @@ -100,8 +100,8 @@ export const getShowPetByIdKey = (petId: string,
version= 1,) => [`/v${version}/pets/${petId}`];


export type ShowPetByIdQueryResult = NonNullable<AsyncReturnType<typeof showPetById>>
export type ShowPetByIdQueryError = Error
export type ShowPetByIdQueryResult = NonNullable<AsyncReturnType<typeof showPetById>>
export type ShowPetByIdQueryError = Error

export const useShowPetById = <TError = Error>(
petId: string,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ export const createPets = (


export type CreatePetsMutationResult = NonNullable<AsyncReturnType<typeof createPets>>
export type CreatePetsMutationBody = CreatePetsBody
export type CreatePetsMutationError = ErrorType<Error>

export const useCreatePets = <TError = ErrorType<Error>,
Expand Down
23 changes: 23 additions & 0 deletions samples/react-query/custom-client/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
54 changes: 54 additions & 0 deletions samples/react-query/custom-client/orval.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import * as faker from 'faker';
import { defineConfig } from 'orval';

export default defineConfig({
petstore: {
output: {
mode: 'split',
target: 'src/api/endpoints/petstoreFromFileSpecWithTransformer.ts',
schemas: 'src/api/model',
client: 'react-query',
mock: true,
override: {
mutator: {
path: './src/api/mutator/custom-client.ts',
name: 'customClient',
},
operations: {
listPets: {
mock: {
properties: () => ({
'[].id': () => faker.random.number({ min: 1, max: 99999 }),
}),
},
},
showPetById: {
mock: {
data: () => ({
id: faker.random.number({ min: 1, max: 99 }),
name: faker.name.firstName(),
tag: faker.helpers.randomize([faker.random.word(), undefined]),
}),
},
},
},
mock: {
properties: {
'/tag|name/': () => faker.name.lastName(),
},
},
query: {
useQuery: true,
useInfinite: true,
useInfiniteQueryParam: 'limit',
},
},
},
input: {
target: './petstore.yaml',
override: {
transformer: './src/api/transformer/add-version.js',
},
},
},
});
43 changes: 43 additions & 0 deletions samples/react-query/custom-client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"name": "react-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@types/faker": "^5.5.6",
"@types/node": "^14.14.13",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"axios": "^0.21.0",
"faker": "^5.5.3",
"msw": "^0.24.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-query": "^3.17.1",
"react-scripts": "^4.0.1",
"typescript": "^4.1.3"
},
"devDependencies": {
"orval": "link:../../../dist"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject",
"generate-api": "node ../../../dist/bin/orval.js"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
146 changes: 146 additions & 0 deletions samples/react-query/custom-client/petstore.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
openapi: '3.0.0'
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
servers:
- url: http://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: string
responses:
'200':
description: A paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: '#/components/schemas/Pets'
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
post:
summary: Create a pet
operationId: createPets
tags:
- pets
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- 'name'
- 'tag'
properties:
name:
type: string
tag:
type: string
responses:
'200':
description: Created Pet
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
- name: testId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
Pet:
type: object
required:
- id
- name
properties:
'@id':
type: string
format: iri-reference
id:
type: integer
format: int64
name:
type: string
tag:
type: string
email:
type: string
format: email
callingCode:
type: string
enum: ['+33', '+420', '+33'] # intentional duplicated value
country:
type: string
enum: ["People's Republic of China", 'Uruguay']
Pets:
type: array
items:
$ref: '#/components/schemas/Pet'
Error:
type: object
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
Binary file not shown.
43 changes: 43 additions & 0 deletions samples/react-query/custom-client/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions samples/react-query/custom-client/public/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
Loading