Skip to content

Commit

Permalink
fix: escape enum values (orval-labs#212)
Browse files Browse the repository at this point in the history
* feat(utils): add escape function

* fix: escape enum values

* test: add an enum in petstore

* test: add a duplicated enum value
  • Loading branch information
alanpoulain authored Sep 29, 2021
1 parent b42fd82 commit 8878a2e
Show file tree
Hide file tree
Showing 9 changed files with 87 additions and 14 deletions.
5 changes: 4 additions & 1 deletion samples/react-app-with-react-query/petstore.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,10 @@ components:
format: email
callingCode:
type: string
enum: ['+33', '+420']
enum: ['+33', '+420', '+33'] # intentional duplicated value
country:
type: string
enum: ["People's Republic of China", 'Uruguay']
Pets:
type: array
items:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ import type {
Pet
} from '../model'

export const getListPetsMock = () => ([...Array(faker.datatype.number({min: 1, max: 10}))].map(() => ({'@id': faker.helpers.randomize([faker.random.word(), undefined]), id: (()=>faker.random.number({min:1,max:99999}))(), name: (()=>faker.name.lastName())(), tag: (()=>faker.name.lastName())(), email: faker.helpers.randomize([faker.internet.email(), undefined]), callingCode: faker.helpers.randomize([faker.helpers.randomize(['+33','+420']), undefined])})))
export const getListPetsMock = () => ([...Array(faker.datatype.number({min: 1, max: 10}))].map(() => ({'@id': faker.helpers.randomize([faker.random.word(), undefined]), id: (()=>faker.random.number({min:1,max:99999}))(), name: (()=>faker.name.lastName())(), tag: (()=>faker.name.lastName())(), email: faker.helpers.randomize([faker.internet.email(), undefined]), callingCode: faker.helpers.randomize([faker.helpers.randomize(['+33','+420','+33']), undefined]), country: faker.helpers.randomize([faker.helpers.randomize(['People's Republic of China','Uruguay']), undefined])})))
export const getCreatePetsMock = () => ({'@id': faker.helpers.randomize([faker.random.word(), undefined]), id: faker.datatype.number(), name: (()=>faker.name.lastName())(), tag: (()=>faker.name.lastName())(), email: faker.helpers.randomize([faker.internet.email(), undefined]), callingCode: faker.helpers.randomize([faker.helpers.randomize(['+33','+420']), undefined])})
export const getCreatePetsMock = () => ({'@id': faker.helpers.randomize([faker.random.word(), undefined]), id: faker.datatype.number(), name: (()=>faker.name.lastName())(), tag: (()=>faker.name.lastName())(), email: faker.helpers.randomize([faker.internet.email(), undefined]), callingCode: faker.helpers.randomize([faker.helpers.randomize(['+33','+420','+33']), undefined]), country: faker.helpers.randomize([faker.helpers.randomize(['People's Republic of China','Uruguay']), undefined])})
export const getShowPetByIdMock = () => ((()=>({id:faker.random.number({min:1,max:99}),name:faker.name.firstName(),tag:faker.helpers.randomize([faker.random.word(),void 0])}))())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,13 @@
*/
import {
useQuery,
useInfiniteQuery,
useMutation,
UseQueryOptions,
UseMutationOptions
UseInfiniteQueryOptions,
UseMutationOptions,
QueryFunction,
MutationFunction
} from 'react-query'
import type {
Pets,
Expand Down Expand Up @@ -43,6 +47,25 @@ export const getListPetsQueryKey = (params?: ListPetsParams,
version= 1,) => [`/v${version}/pets`, ...(params ? [params]: [])];


export const useListPetsInfinite = <TData = AsyncReturnType<typeof listPets>, TError = Error>(
params?: ListPetsParams,
version= 1, options?: { query?:UseInfiniteQueryOptions<AsyncReturnType<typeof listPets>, TError, TData>, }

) => {

const {query: queryOptions} = options || {}

const queryKey = queryOptions?.queryKey ?? getListPetsQueryKey(params,version);
const queryFn: QueryFunction<AsyncReturnType<typeof listPets>> = ({ pageParam }) => listPets({ limit: pageParam, ...params },version, );

const query = useInfiniteQuery<AsyncReturnType<typeof listPets>, TError, TData>(queryKey, queryFn, {enabled: !!(version), ...queryOptions})

return {
queryKey,
...query
}
}

export const useListPets = <TData = AsyncReturnType<typeof listPets>, TError = Error>(
params?: ListPetsParams,
version= 1, options?: { query?:UseQueryOptions<AsyncReturnType<typeof listPets>, TError, TData>, }
Expand All @@ -52,9 +75,9 @@ export const useListPets = <TData = AsyncReturnType<typeof listPets>, TError = E
const {query: queryOptions} = options || {}

const queryKey = queryOptions?.queryKey ?? getListPetsQueryKey(params,version);
const queryFn = () => listPets(params,version, );
const queryFn: QueryFunction<AsyncReturnType<typeof listPets>> = () => listPets(params,version, );

const query = useQuery<AsyncReturnType<typeof queryFn>, TError, TData>(queryKey, queryFn, {enabled: !!(version), ...queryOptions})
const query = useQuery<AsyncReturnType<typeof listPets>, TError, TData>(queryKey, queryFn, {enabled: !!(version), ...queryOptions})

return {
queryKey,
Expand Down Expand Up @@ -85,11 +108,13 @@ export const createPets = (
) => {
const {mutation: mutationOptions} = options || {}

return useMutation<AsyncReturnType<typeof createPets>, TError, {data: CreatePetsBody;version?: number}, TContext>((props) => {
const {data,version} = props || {};
const mutationFn: MutationFunction<AsyncReturnType<typeof createPets>, {data: CreatePetsBody;version?: number}> = (props) => {
const {data,version} = props || {};

return createPets(data,version,)
}

return createPets(data,version,)
}, mutationOptions)
return useMutation<AsyncReturnType<typeof createPets>, TError, {data: CreatePetsBody;version?: number}, TContext>(mutationFn, mutationOptions)
}

/**
Expand All @@ -110,6 +135,25 @@ export const getShowPetByIdQueryKey = (petId: string,
version= 1,) => [`/v${version}/pets/${petId}`];


export const useShowPetByIdInfinite = <TData = AsyncReturnType<typeof showPetById>, TError = Error>(
petId: string,
version= 1, options?: { query?:UseInfiniteQueryOptions<AsyncReturnType<typeof showPetById>, TError, TData>, }

) => {

const {query: queryOptions} = options || {}

const queryKey = queryOptions?.queryKey ?? getShowPetByIdQueryKey(petId,version);
const queryFn: QueryFunction<AsyncReturnType<typeof showPetById>> = () => showPetById(petId,version, );

const query = useInfiniteQuery<AsyncReturnType<typeof showPetById>, TError, TData>(queryKey, queryFn, {enabled: !!(version && petId), ...queryOptions})

return {
queryKey,
...query
}
}

export const useShowPetById = <TData = AsyncReturnType<typeof showPetById>, TError = Error>(
petId: string,
version= 1, options?: { query?:UseQueryOptions<AsyncReturnType<typeof showPetById>, TError, TData>, }
Expand All @@ -119,9 +163,9 @@ export const useShowPetById = <TData = AsyncReturnType<typeof showPetById>, TErr
const {query: queryOptions} = options || {}

const queryKey = queryOptions?.queryKey ?? getShowPetByIdQueryKey(petId,version);
const queryFn = () => showPetById(petId,version, );
const queryFn: QueryFunction<AsyncReturnType<typeof showPetById>> = () => showPetById(petId,version, );

const query = useQuery<AsyncReturnType<typeof queryFn>, TError, TData>(queryKey, queryFn, {enabled: !!(version && petId), ...queryOptions})
const query = useQuery<AsyncReturnType<typeof showPetById>, TError, TData>(queryKey, queryFn, {enabled: !!(version && petId), ...queryOptions})

return {
queryKey,
Expand Down
1 change: 1 addition & 0 deletions samples/react-app-with-react-query/src/api/model/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export * from './listPetsParams';
export * from './pet';
export * from './pets';
export * from './petCallingCode';
export * from './petCountry';
2 changes: 2 additions & 0 deletions samples/react-app-with-react-query/src/api/model/pet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* OpenAPI spec version: 1.0.0
*/
import type { PetCallingCode } from './petCallingCode';
import type { PetCountry } from './petCountry';

export interface Pet {
'@id'?: string;
Expand All @@ -13,4 +14,5 @@ export interface Pet {
tag?: string;
email?: string;
callingCode?: PetCallingCode;
country?: PetCountry;
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* OpenAPI spec version: 1.0.0
*/

export type PetCallingCode = '+33' | '+420';
export type PetCallingCode = '+33' | '+420' | '+33';


export const PetCallingCode = {
Expand Down
14 changes: 14 additions & 0 deletions samples/react-app-with-react-query/src/api/model/petCountry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Generated by orval v6.1.1 🍺
* Do not edit manually.
* Swagger Petstore
* OpenAPI spec version: 1.0.0
*/

export type PetCountry = 'People\'s Republic of China' | 'Uruguay';


export const PetCountry = {
Peoples_Republic_of_China: 'People\'s Republic of China' as PetCountry,
Uruguay: 'Uruguay' as PetCountry,
};
8 changes: 7 additions & 1 deletion src/core/getters/scalar.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { SchemaObject } from 'openapi3-ts';
import { ContextSpecs } from '../../types';
import { ResolverValue } from '../../types/resolvers';
import { isString } from '../../utils/is';
import { escape } from '../../utils/string';
import { getArray } from './array';
import { getObject } from './object';

Expand Down Expand Up @@ -73,7 +75,11 @@ export const getScalar = async ({
let isEnum = false;

if (item.enum) {
value = `'${item.enum.join(`' | '`)}'`;
value = `'${item.enum
.map((enumItem: string) =>
isString(enumItem) ? escape(enumItem) : enumItem,
)
.join(`' | '`)}'`;
isEnum = true;
}

Expand Down
3 changes: 3 additions & 0 deletions src/utils/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,6 @@ export const getNumberWord = (num: number) => {
const arrayOfNumber = num.toString().split('') as (keyof typeof NUMBERS)[];
return arrayOfNumber.reduce((acc, n) => acc + NUMBERS[n], '');
};

export const escape = (str: string, char: string = "'") =>
str.replace(char, `\\${char}`);

0 comments on commit 8878a2e

Please sign in to comment.