Skip to content

Commit 313c8b0

Browse files
georgiev-antonmelloware
andauthoredNov 7, 2023
feat(query): add prefetch functions (#956)
* feat(query): add prefetch functions * feat(query): add prefetch functions doc * feat(query): prefetch functions add types * feat(query): prefetch functions generate samples * feat(query): prefetch functions fix pageParam * feat(query): prefetch functions fix samples * Update object.ts * feat(query): prefetch functions fix after review --------- Co-authored-by: Melloware <mellowaredev@gmail.com>
1 parent 7a95876 commit 313c8b0

File tree

12 files changed

+94
-31
lines changed

12 files changed

+94
-31
lines changed
 

‎CODE_OF_CONDUCT.md

+12-12
Original file line numberDiff line numberDiff line change
@@ -17,23 +17,23 @@ diverse, inclusive, and healthy community.
1717
Examples of behavior that contributes to a positive environment for our
1818
community include:
1919

20-
* Demonstrating empathy and kindness toward other people
21-
* Being respectful of differing opinions, viewpoints, and experiences
22-
* Giving and gracefully accepting constructive feedback
23-
* Accepting responsibility and apologizing to those affected by our mistakes,
20+
- Demonstrating empathy and kindness toward other people
21+
- Being respectful of differing opinions, viewpoints, and experiences
22+
- Giving and gracefully accepting constructive feedback
23+
- Accepting responsibility and apologizing to those affected by our mistakes,
2424
and learning from the experience
25-
* Focusing on what is best not just for us as individuals, but for the overall
25+
- Focusing on what is best not just for us as individuals, but for the overall
2626
community
2727

2828
Examples of unacceptable behavior include:
2929

30-
* The use of sexualized language or imagery, and sexual attention or advances of
30+
- The use of sexualized language or imagery, and sexual attention or advances of
3131
any kind
32-
* Trolling, insulting or derogatory comments, and personal or political attacks
33-
* Public or private harassment
34-
* Publishing others' private information, such as a physical or email address,
32+
- Trolling, insulting or derogatory comments, and personal or political attacks
33+
- Public or private harassment
34+
- Publishing others' private information, such as a physical or email address,
3535
without their explicit permission
36-
* Other conduct which could reasonably be considered inappropriate in a
36+
- Other conduct which could reasonably be considered inappropriate in a
3737
professional setting
3838

3939
## Enforcement Responsibilities
@@ -119,8 +119,8 @@ version 2.1, available at
119119
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120120

121121
Community Impact Guidelines were inspired by
122-
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
122+
[Mozilla's code of conduct enforcement ladder][mozilla coc].
123123

124124
For answers to common questions about this code of conduct, see the FAQ at
125-
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
125+
[https://www.contributor-covenant.org/faq][faq]. Translations are available at
126126
[https://www.contributor-covenant.org/translations][translations].

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ You can find below some samples
3131
- [angular app](https://github.com/anymaniax/orval/tree/master/samples/angular-app)
3232

3333
### All Thanks To Our Contributors:
34+
3435
<a href="https://github.com/anymaniax/orval/graphs/contributors">
3536
<img src="https://contrib.rocks/image?repo=anymaniax/orval" />
3637
</a>

‎docs/src/pages/reference/configuration/output.md

+33-1
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,38 @@ Type: `Boolean`.
565565

566566
Use to generate a <a href="https://tanstack.com/query/latest/docs/react/reference/useInfiniteQuery" target="_blank">useInfiniteQuery</a> custom hook.
567567

568+
##### usePrefetch
569+
570+
Type: `Boolean`.
571+
572+
Use to generate a <a href="https://tanstack.com/query/v4/docs/react/guides/prefetching" target="_blank">prefetching</a> functions.
573+
This may be useful for the NextJS SSR or any prefetching situations.
574+
575+
Example generated function:
576+
577+
```js
578+
export const prefetchGetCategories = async <
579+
TData = Awaited<ReturnType<typeof getCategories>>,
580+
TError = ErrorType<unknown>,
581+
>(
582+
queryClient: QueryClient,
583+
options?: {
584+
query?: UseQueryOptions<
585+
Awaited<ReturnType<typeof getCategories>>,
586+
TError,
587+
TData,
588+
>,
589+
request?: SecondParameter<typeof customAxiosInstance>,
590+
},
591+
): Promise<QueryClient> => {
592+
const queryOptions = getGetCategoriesQueryOptions(options);
593+
594+
await queryClient.prefetchQuery(queryOptions);
595+
596+
return queryClient;
597+
};
598+
```
599+
568600
##### useInfiniteQueryParam
569601

570602
Type: `String`.
@@ -691,7 +723,7 @@ module.exports = {
691723
mock: {
692724
properties: {
693725
'/tag|name/': 'jon', // Matches every property named 'tag' or 'name', including nested ones
694-
'/.*\.user\.id/': faker.string.uuid(), // Matches every property named 'id', inside an object named 'user', including nested ones
726+
'/.*.user.id/': faker.string.uuid(), // Matches every property named 'id', inside an object named 'user', including nested ones
695727
email: () => faker.internet.email(), // Matches only the property 'email'
696728
'user.id': () => faker.string.uuid(), // Matches only the full path 'user.id'
697729
},

‎packages/core/src/getters/object.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -181,8 +181,7 @@ export const getObject = ({
181181
}
182182

183183
return {
184-
value:
185-
(item.type === 'object' ? '{ [key: string]: any }' : 'unknown') + nullable,
184+
value: (item.type === 'object' ? '{ [key: string]: any }' : 'unknown') + nullable,
186185
imports: [],
187186
schemas: [],
188187
isEnum: false,

‎packages/core/src/types.ts

+2
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,7 @@ export type NormalizedQueryOptions = {
316316
useInfinite?: boolean;
317317
useSuspenseInfiniteQuery?: boolean;
318318
useInfiniteQueryParam?: string;
319+
usePrefetch?: boolean;
319320
options?: any;
320321
queryKey?: NormalizedMutator;
321322
queryOptions?: NormalizedMutator;
@@ -331,6 +332,7 @@ export type QueryOptions = {
331332
useInfinite?: boolean;
332333
useSuspenseInfiniteQuery?: boolean;
333334
useInfiniteQueryParam?: string;
335+
usePrefetch?: boolean;
334336
options?: any;
335337
queryKey?: Mutator;
336338
queryOptions?: Mutator;

‎packages/core/src/writers/schemas.ts

+11-11
Original file line numberDiff line numberDiff line change
@@ -116,21 +116,21 @@ export const writeSchemas = async ({
116116
const stringData = data.toString();
117117

118118
const importStatements = schemas
119-
.filter((schema) => {
120-
return (
121-
!stringData.includes(`export * from './${camel(schema.name)}'`) &&
122-
!stringData.includes(`export * from "./${camel(schema.name)}"`)
123-
);
124-
})
125-
.map((schema) => `export * from './${camel(schema.name)}';`);
119+
.filter((schema) => {
120+
return (
121+
!stringData.includes(`export * from './${camel(schema.name)}'`) &&
122+
!stringData.includes(`export * from "./${camel(schema.name)}"`)
123+
);
124+
})
125+
.map((schema) => `export * from './${camel(schema.name)}';`);
126126

127127
const currentFileExports = (stringData
128-
.match(/export \* from(.*)('|")/g)
129-
?.map((s) => s + ';') ?? []) as string[];
128+
.match(/export \* from(.*)('|")/g)
129+
?.map((s) => s + ';') ?? []) as string[];
130130

131131
const exports = [...currentFileExports, ...importStatements]
132-
.sort()
133-
.join('\n');
132+
.sort()
133+
.join('\n');
134134

135135
const fileContent = `${header}\n${exports}`;
136136

‎packages/orval/src/utils/options.ts

+3
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,9 @@ const normalizeQueryOptions = (
381381
}
382382

383383
return {
384+
...(!isUndefined(queryOptions.usePrefetch)
385+
? { usePrefetch: queryOptions.usePrefetch }
386+
: {}),
384387
...(!isUndefined(queryOptions.useQuery)
385388
? { useQuery: queryOptions.useQuery }
386389
: {}),

‎packages/query/src/index.ts

+23-1
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ const REACT_QUERY_DEPENDENCIES_V3: GeneratorDependency[] = [
154154
{ name: 'UseQueryResult' },
155155
{ name: 'UseInfiniteQueryResult' },
156156
{ name: 'QueryKey' },
157+
{ name: 'QueryClient' },
157158
],
158159
dependency: 'react-query',
159160
},
@@ -178,6 +179,7 @@ const REACT_QUERY_DEPENDENCIES: GeneratorDependency[] = [
178179
{ name: 'UseInfiniteQueryResult' },
179180
{ name: 'UseSuspenseInfiniteQueryResult' },
180181
{ name: 'QueryKey' },
182+
{ name: 'QueryClient' },
181183
{ name: 'InfiniteData' },
182184
],
183185
dependency: '@tanstack/react-query',
@@ -803,6 +805,7 @@ const generateQueryImplementation = ({
803805
hasSvelteQueryV4,
804806
hasQueryV5,
805807
doc,
808+
usePrefetch,
806809
}: {
807810
queryOption: {
808811
name: string;
@@ -830,6 +833,7 @@ const generateQueryImplementation = ({
830833
hasSvelteQueryV4: boolean;
831834
hasQueryV5: boolean;
832835
doc?: string;
836+
usePrefetch?: boolean;
833837
}) => {
834838
const queryProps = toObjectString(props, 'implementation');
835839

@@ -1031,7 +1035,24 @@ ${doc}export const ${camel(
10311035
};
10321036
10331037
return query;
1034-
}\n`;
1038+
}\n
1039+
${
1040+
usePrefetch
1041+
? `${doc}export const ${camel(
1042+
`prefetch-${name}`,
1043+
)} = async <TData = Awaited<ReturnType<${dataType}>>, TError = ${errorType}>(\n queryClient: QueryClient, ${queryProps} ${queryArguments}\n ): Promise<QueryClient> => {
1044+
1045+
const ${queryOptionsVarName} = ${queryOptionsFnName}(${queryProperties}${
1046+
queryProperties ? ',' : ''
1047+
}${isRequestOptions ? 'options' : 'queryOptions'})
1048+
1049+
await queryClient.${camel(`prefetch-${type}`)}(${queryOptionsVarName});
1050+
1051+
return queryClient;
1052+
}\n`
1053+
: ''
1054+
}
1055+
`;
10351056
};
10361057

10371058
const generateQueryHook = async (
@@ -1218,6 +1239,7 @@ const generateQueryHook = async (
12181239
hasSvelteQueryV4,
12191240
hasQueryV5,
12201241
doc,
1242+
usePrefetch: query.usePrefetch,
12211243
}),
12221244
'',
12231245
)}

‎packages/query/src/utils.ts

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ export const normalizeQueryOptions = (
1919
outputWorkspace: string,
2020
): NormalizedQueryOptions => {
2121
return {
22+
...(queryOptions.usePrefetch ? { usePrefetch: true } : {}),
2223
...(queryOptions.useQuery ? { useQuery: true } : {}),
2324
...(queryOptions.useInfinite ? { useInfinite: true } : {}),
2425
...(queryOptions.useInfiniteQueryParam

‎packages/zod/src/index.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,7 @@ const parseZodValidationSchemaDefinition = (
279279
if (fn === 'additionalProperties') {
280280
const value = args.functions.map(parseProperty).join('');
281281
const valueWithZod = `${value.startsWith('.') ? 'zod' : ''}${value}`;
282-
consts += args.consts
282+
consts += args.consts;
283283
return `zod.record(zod.string(), ${valueWithZod})`;
284284
}
285285

‎samples/react-query/basic/src/api/endpoints/petstoreFromFileSpecWithTransformer.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,8 @@ export const getListPetsInfiniteQueryOptions = <
117117
Awaited<ReturnType<typeof listPets>>,
118118
QueryKey,
119119
ListPetsParams['limit']
120-
> = ({ pageParam }) => listPets({ limit: pageParam, ...params }, version);
120+
> = ({ pageParam }) =>
121+
listPets({ ...params, limit: pageParam || params.page }, version);
121122

122123
return {
123124
queryKey,
@@ -348,7 +349,8 @@ export const getListPetsSuspenseInfiniteQueryOptions = <
348349
Awaited<ReturnType<typeof listPets>>,
349350
QueryKey,
350351
ListPetsParams['limit']
351-
> = ({ pageParam }) => listPets({ limit: pageParam, ...params }, version);
352+
> = ({ pageParam }) =>
353+
listPets({ ...params, limit: pageParam || params.page }, version);
352354

353355
return {
354356
queryKey,

‎samples/vue-query/src/api/endpoints/petstoreFromFileSpecWithTransformer.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,8 @@ export const getListPetsInfiniteQueryOptions = <
7979
const queryFn: QueryFunction<Awaited<ReturnType<typeof listPets>>> = ({
8080
signal,
8181
pageParam,
82-
}) => listPets({ limit: pageParam, ...params }, version, signal);
82+
}) =>
83+
listPets({ ...params, limit: pageParam || params.page }, version, signal);
8384

8485
return {
8586
queryKey,

0 commit comments

Comments
 (0)
Please sign in to comment.