Skip to content

Commit

Permalink
fix: manage enum plus number (orval-labs#213)
Browse files Browse the repository at this point in the history
* fix: manage plus number in enum and use isIdentifierNameES5 for key

* test: add an enum in petstore
  • Loading branch information
alanpoulain authored Sep 28, 2021
1 parent 09ea830 commit 9f61489
Show file tree
Hide file tree
Showing 11 changed files with 146 additions and 135 deletions.
3 changes: 3 additions & 0 deletions samples/react-app-with-react-query/petstore.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@ components:
email:
type: string
format: email
callingCode:
type: string
enum: ['+33', '+420']
Pets:
type: array
items:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Generated by orval v6.0.0 🍺
* Generated by orval v6.1.1 🍺
* Do not edit manually.
* Swagger Petstore
* OpenAPI spec version: 1.0.0
Expand All @@ -13,23 +13,11 @@ 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.datatype.number(), name: (function() {
return faker.name.lastName();
})(), tag: (function() {
return faker.name.lastName();
})(), email: faker.helpers.randomize([faker.internet.email(), 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']), undefined])})))

export const getCreatePetsMock = () => ({'@id': faker.helpers.randomize([faker.random.word(), undefined]), id: faker.datatype.number(), name: (function() {
return faker.name.lastName();
})(), tag: (function() {
return faker.name.lastName();
})(), email: faker.helpers.randomize([faker.internet.email(), 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 getShowPetByIdMock = () => ({'@id': faker.helpers.randomize([faker.random.word(), undefined]), id: faker.datatype.number(), name: (function() {
return faker.name.lastName();
})(), tag: (function() {
return faker.name.lastName();
})(), email: faker.helpers.randomize([faker.internet.email(), 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])}))())

export const getSwaggerPetstoreMSW = () => [
rest.get('*/v:version/pets', (req, res, ctx) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,135 +1,132 @@
/**
* Generated by orval v6.0.0 🍺
* Generated by orval v6.1.1 🍺
* Do not edit manually.
* Swagger Petstore
* OpenAPI spec version: 1.0.0
*/
import {
useMutation,
UseMutationOptions,
useQuery,
useMutation,
UseQueryOptions,
} from 'react-query';
UseMutationOptions
} from 'react-query'
import type {
CreatePetsBody,
Pets,
Error,
ListPetsParams,
Pet,
Pets,
} from '../model';
import { customInstance } from '../mutator/custom-instance';

type AsyncReturnType<T extends (...args: any) => Promise<any>> = T extends (
...args: any
) => Promise<infer R>
? R
: any;

export const listPets = (params?: ListPetsParams, version = 1) => {
return customInstance<Pets>({
url: `/v${version}/pets`,
method: 'get',
params,
});
};

export const getListPetsQueryKey = (params?: ListPetsParams, version = 1) => [
`/v${version}/pets`,
...(params ? [params] : []),
];

export const useListPets = <
TData = AsyncReturnType<typeof listPets>,
TError = Error,
>(
params?: ListPetsParams,
version = 1,
options?: {
query?: UseQueryOptions<AsyncReturnType<typeof listPets>, TError, TData>;
},
) => {
const { query: queryOptions } = options || {};
CreatePetsBody
} from '../model'
import { customInstance } from '../mutator/custom-instance'

const queryKey =
queryOptions?.queryKey ?? getListPetsQueryKey(params, version);
const queryFn = () => listPets(params, version);
type AsyncReturnType<
T extends (...args: any) => Promise<any>
> = T extends (...args: any) => Promise<infer R> ? R : any;

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

/**
* @summary List all pets
*/
export const listPets = (
params?: ListPetsParams,
version= 1,
) => {
return customInstance<Pets>(
{url: `/v${version}/pets`, method: 'get',
params,
},
);
}


export const getListPetsQueryKey = (params?: ListPetsParams,
version= 1,) => [`/v${version}/pets`, ...(params ? [params]: [])];


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

) => {

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

const queryKey = queryOptions?.queryKey ?? getListPetsQueryKey(params,version);
const queryFn = () => listPets(params,version, );

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

return {
queryKey,
...query,
};
};

export const createPets = (createPetsBody: CreatePetsBody, version = 1) => {
return customInstance<Pet>({
url: `/v${version}/pets`,
method: 'post',
data: createPetsBody,
});
};

export const useCreatePets = <TError = Error, TContext = unknown>(options?: {
mutation?: UseMutationOptions<
AsyncReturnType<typeof createPets>,
TError,
{ data: CreatePetsBody; version?: number },
TContext
>;
}) => {
const { mutation: mutationOptions } = options || {};

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

return createPets(data, version);
}, mutationOptions);
};
export const showPetById = (petId: string, version = 1) => {
return customInstance<Pet>({
url: `/v${version}/pets/${petId}`,
method: 'get',
});
};

export const getShowPetByIdQueryKey = (petId: string, version = 1) => [
`/v${version}/pets/${petId}`,
];

export const useShowPetById = <
TData = AsyncReturnType<typeof showPetById>,
TError = Error,
>(
petId: string,
version = 1,
options?: {
query?: UseQueryOptions<AsyncReturnType<typeof showPetById>, TError, TData>;
},
...query
}
}


/**
* @summary Create a pet
*/
export const createPets = (
createPetsBody: CreatePetsBody,
version= 1,
) => {
return customInstance<Pet>(
{url: `/v${version}/pets`, method: 'post',
data: createPetsBody
},
);
}



export const useCreatePets = <TError = Error,

TContext = unknown>(options?: { mutation?:UseMutationOptions<AsyncReturnType<typeof createPets>, TError,{data: CreatePetsBody;version?: number}, TContext>, }
) => {
const { query: queryOptions } = options || {};
const {mutation: mutationOptions} = options || {}

const queryKey =
queryOptions?.queryKey ?? getShowPetByIdQueryKey(petId, version);
const queryFn = () => showPetById(petId, version);
return useMutation<AsyncReturnType<typeof createPets>, TError, {data: CreatePetsBody;version?: number}, TContext>((props) => {
const {data,version} = props || {};

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

/**
* @summary Info for a specific pet
*/
export const showPetById = (
petId: string,
version= 1,
) => {
return customInstance<Pet>(
{url: `/v${version}/pets/${petId}`, method: 'get'
},
);
}


export const getShowPetByIdQueryKey = (petId: string,
version= 1,) => [`/v${version}/pets/${petId}`];


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

) => {

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

const queryKey = queryOptions?.queryKey ?? getShowPetByIdQueryKey(petId,version);
const queryFn = () => showPetById(petId,version, );

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

return {
queryKey,
...query,
};
};
...query
}
}


Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Generated by orval v6.0.0 🍺
* Generated by orval v6.1.1 🍺
* Do not edit manually.
* Swagger Petstore
* OpenAPI spec version: 1.0.0
Expand Down
2 changes: 1 addition & 1 deletion samples/react-app-with-react-query/src/api/model/error.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Generated by orval v6.0.0 🍺
* Generated by orval v6.1.1 🍺
* Do not edit manually.
* Swagger Petstore
* OpenAPI spec version: 1.0.0
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 @@ -3,3 +3,4 @@ export * from './error';
export * from './listPetsParams';
export * from './pet';
export * from './pets';
export * from './petCallingCode';
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Generated by orval v6.0.0 🍺
* Generated by orval v6.1.1 🍺
* Do not edit manually.
* Swagger Petstore
* OpenAPI spec version: 1.0.0
Expand Down
4 changes: 3 additions & 1 deletion samples/react-app-with-react-query/src/api/model/pet.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
/**
* Generated by orval v6.0.0 🍺
* Generated by orval v6.1.1 🍺
* Do not edit manually.
* Swagger Petstore
* OpenAPI spec version: 1.0.0
*/
import type { PetCallingCode } from './petCallingCode';

export interface Pet {
'@id'?: string;
id: number;
name: string;
tag?: string;
email?: string;
callingCode?: PetCallingCode;
}
14 changes: 14 additions & 0 deletions samples/react-app-with-react-query/src/api/model/petCallingCode.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 PetCallingCode = '+33' | '+420';


export const PetCallingCode = {
NUMBER_PLUS_33: '+33' as PetCallingCode,
NUMBER_PLUS_420: '+420' as PetCallingCode,
};
2 changes: 1 addition & 1 deletion samples/react-app-with-react-query/src/api/model/pets.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Generated by orval v6.0.0 🍺
* Generated by orval v6.1.1 🍺
* Do not edit manually.
* Swagger Petstore
* OpenAPI spec version: 1.0.0
Expand Down
10 changes: 8 additions & 2 deletions src/core/getters/enum.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { keyword } from 'esutils';
import { sanitize } from '../../utils/string';

export const getEnum = (value: string, type: string, enumName: string) => {
Expand All @@ -10,10 +11,12 @@ export const getEnum = (value: string, type: string, enumName: string) => {
isNumber || isTypeNumber
? toNumberKey(isTypeNumber ? val.toString() : val.slice(1, -1))
: sanitize(val, { underscore: '_', whitespace: '_' });
const startWithNumber = !Number.isNaN(+key[0]);

return (
acc + ` ${startWithNumber ? `'${key}'` : key}: ${val} as ${enumName},\n`
acc +
` ${
keyword.isIdentifierNameES5(key) ? key : `'${key}'`
}: ${val} as ${enumName},\n`
);
}, '');

Expand All @@ -26,5 +29,8 @@ const toNumberKey = (value: string) => {
if (value[0] === '-') {
return `NUMBER_MINUS_${value.slice(1)}`;
}
if (value[0] === '+') {
return `NUMBER_PLUS_${value.slice(1)}`;
}
return `NUMBER_${value}`;
};

0 comments on commit 9f61489

Please sign in to comment.