Skip to content
This repository has been archived by the owner on Nov 11, 2023. It is now read-only.

Commit

Permalink
feat: add support for path params is useMutate
Browse files Browse the repository at this point in the history
  • Loading branch information
vkbansal authored and fabien0102 committed Jun 4, 2020
1 parent 12d905c commit f50da00
Show file tree
Hide file tree
Showing 8 changed files with 637 additions and 436 deletions.
23 changes: 15 additions & 8 deletions src/Mutate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,20 @@ export interface States<TData, TError> {
error?: GetState<TData, TError>["error"];
}

export interface MutateRequestOptions<TQueryParams> extends RequestInit {
export interface MutateRequestOptions<TQueryParams, TPathParams> extends RequestInit {
/**
* Query parameters
*/
queryParams?: TQueryParams;
/**
* Path parameters
*/
pathParams?: TPathParams;
}

export type MutateMethod<TData, TRequestBody, TQueryParams> = (
export type MutateMethod<TData, TRequestBody, TQueryParams, TPathParams> = (
data: TRequestBody,
mutateRequestOptions?: MutateRequestOptions<TQueryParams>,
mutateRequestOptions?: MutateRequestOptions<TQueryParams, TPathParams>,
) => Promise<TData>;

/**
Expand All @@ -40,7 +44,7 @@ export interface Meta {
/**
* Props for the <Mutate /> component.
*/
export interface MutateProps<TData, TError, TQueryParams, TRequestBody> {
export interface MutateProps<TData, TError, TQueryParams, TRequestBody, TPathParams = unknown> {
/**
* The path at which to request data,
* typically composed by parents or the RestfulProvider.
Expand Down Expand Up @@ -83,7 +87,7 @@ export interface MutateProps<TData, TError, TQueryParams, TRequestBody> {
* @param actions - a key/value map of HTTP verbs, aliasing destroy to DELETE.
*/
children: (
mutate: MutateMethod<TData, TRequestBody, TQueryParams>,
mutate: MutateMethod<TData, TRequestBody, TQueryParams, TPathParams>,
states: States<TData, TError>,
meta: Meta,
) => React.ReactNode;
Expand Down Expand Up @@ -111,8 +115,8 @@ export interface MutateState<TData, TError> {
* is a named class because it is useful in
* debugging.
*/
class ContextlessMutate<TData, TError, TQueryParams, TRequestBody> extends React.Component<
MutateProps<TData, TError, TQueryParams, TRequestBody> & InjectedProps,
class ContextlessMutate<TData, TError, TQueryParams, TRequestBody, TPathParams = unknown> extends React.Component<
MutateProps<TData, TError, TQueryParams, TRequestBody, TPathParams> & InjectedProps,
MutateState<TData, TError>
> {
public readonly state: Readonly<MutateState<TData, TError>> = {
Expand All @@ -137,7 +141,10 @@ class ContextlessMutate<TData, TError, TQueryParams, TRequestBody> extends React
this.abortController.abort();
}

public mutate = async (body: TRequestBody, mutateRequestOptions?: MutateRequestOptions<TQueryParams>) => {
public mutate = async (
body: TRequestBody,
mutateRequestOptions?: MutateRequestOptions<TQueryParams, TPathParams>,
) => {
const {
__internal_hasExplicitBase,
base,
Expand Down
24 changes: 16 additions & 8 deletions src/scripts/import-open-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ export const generateRestfulComponent = (
throw new Error(`The path params ${p} can't be found in parameters (${operation.operationId})`);
}
})
.join("; ");
.join(";\n ");

const queryParamsType = queryParams
.map(p => {
Expand Down Expand Up @@ -399,7 +399,7 @@ export const generateRestfulComponent = (
verb === "get"
? `${needAResponseComponent ? componentName + "Response" : responseTypes}, ${
queryParamsType ? componentName + "QueryParams" : "void"
}`
}, ${paramsInPath.length ? componentName + "PathParams" : "void"}`
: `${needAResponseComponent ? componentName + "Response" : responseTypes}, ${
queryParamsType ? componentName + "QueryParams" : "void"
}, ${
Expand All @@ -408,7 +408,7 @@ export const generateRestfulComponent = (
: needARequestBodyComponent
? componentName + "RequestBody"
: requestBodyTypes
}`;
}, ${paramsInPath.length ? componentName + "PathParams" : "void"}`;

const customPropsEntries = Object.entries(customProps);

Expand All @@ -432,6 +432,14 @@ export ${
export interface ${componentName}QueryParams {
${queryParamsType};
}
`
: ""
}${
paramsInPath.length
? `
export interface ${componentName}PathParams {
${paramsTypes}
}
`
: ""
}${
Expand Down Expand Up @@ -468,19 +476,19 @@ ${description}export const ${componentName} = (${
// Hooks version
output += `export type Use${componentName}Props = Omit<Use${Component}Props<${genericsTypesForHooksProps}>, "path"${
verb === "get" ? "" : ` | "verb"`
}>${paramsInPath.length ? ` & {${paramsTypes}}` : ""};
}>${paramsInPath.length ? ` & ${componentName}PathParams` : ""};
${description}export const use${componentName} = (${
paramsInPath.length ? `{${paramsInPath.join(", ")}, ...props}` : "props"
}: Use${componentName}Props) => use${Component}<${genericsTypes}>(${
verb === "get" ? "" : `"${verb.toUpperCase()}", `
}\`${route}\`, ${
}${paramsInPath.length ? `({ ${paramsInPath.join(", ")} }) => \`${route}\`` : `\`${route}\``}, { ${
customPropsEntries.length
? `{ ${customPropsEntries
.map(([key, value]) => `${key}:${reactPropsValueToObjectValue(value || "")}`)
.join(", ")}, ...props}`
: "props"
});
.join(", ")}, `
: ""
}${paramsInPath.length ? `pathParams: { ${paramsInPath.join(", ")} }, ` : ""}...props });
`;

Expand Down
28 changes: 18 additions & 10 deletions src/scripts/tests/__snapshots__/import-open-api.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export const FindPets = (props: FindPetsProps) => (
/>
);
export type UseFindPetsProps = Omit<UseGetProps<Pet[], FindPetsQueryParams>, \\"path\\">;
export type UseFindPetsProps = Omit<UseGetProps<Pet[], FindPetsQueryParams, void>, \\"path\\">;
/**
* Returns all pets from the system that the user has access to
Expand All @@ -97,7 +97,7 @@ export type UseFindPetsProps = Omit<UseGetProps<Pet[], FindPetsQueryParams>, \\"
* Sed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien.
*
*/
export const useFindPets = (props: UseFindPetsProps) => useGet<Pet[], Error, FindPetsQueryParams>(\`/pets\`, props);
export const useFindPets = (props: UseFindPetsProps) => useGet<Pet[], Error, FindPetsQueryParams>(\`/pets\`, { ...props });
export type AddPetProps = Omit<MutateProps<Pet, Error, void, NewPet>, \\"path\\" | \\"verb\\">;
Expand All @@ -113,14 +113,18 @@ export const AddPet = (props: AddPetProps) => (
/>
);
export type UseAddPetProps = Omit<UseMutateProps<Pet, void, NewPet>, \\"path\\" | \\"verb\\">;
export type UseAddPetProps = Omit<UseMutateProps<Pet, void, NewPet, void>, \\"path\\" | \\"verb\\">;
/**
* Creates a new pet in the store. Duplicates are allowed
*/
export const useAddPet = (props: UseAddPetProps) => useMutate<Pet, Error, void, NewPet>(\\"POST\\", \`/pets\`, props);
export const useAddPet = (props: UseAddPetProps) => useMutate<Pet, Error, void, NewPet>(\\"POST\\", \`/pets\`, { ...props });
export interface FindPetByIdPathParams {
id: number
}
export type FindPetByIdProps = Omit<GetProps<Pet, Error, void>, \\"path\\"> & {id: number};
/**
Expand All @@ -133,12 +137,12 @@ export const FindPetById = ({id, ...props}: FindPetByIdProps) => (
/>
);
export type UseFindPetByIdProps = Omit<UseGetProps<Pet, void>, \\"path\\"> & {id: number};
export type UseFindPetByIdProps = Omit<UseGetProps<Pet, void, FindPetByIdPathParams>, \\"path\\"> & FindPetByIdPathParams;
/**
* Returns a user based on a single ID, if the user does not have access to the pet
*/
export const useFindPetById = ({id, ...props}: UseFindPetByIdProps) => useGet<Pet, Error, void>(\`/pets/\${id}\`, props);
export const useFindPetById = ({id, ...props}: UseFindPetByIdProps) => useGet<Pet, Error, void>(({ id }) => \`/pets/\${id}\`, { pathParams: { id }, ...props });
export type DeletePetProps = Omit<MutateProps<void, Error, void, number>, \\"path\\" | \\"verb\\">;
Expand All @@ -154,14 +158,18 @@ export const DeletePet = (props: DeletePetProps) => (
/>
);
export type UseDeletePetProps = Omit<UseMutateProps<void, void, number>, \\"path\\" | \\"verb\\">;
export type UseDeletePetProps = Omit<UseMutateProps<void, void, number, void>, \\"path\\" | \\"verb\\">;
/**
* deletes a single pet based on the ID supplied
*/
export const useDeletePet = (props: UseDeletePetProps) => useMutate<void, Error, void, number>(\\"DELETE\\", \`/pets\`, props);
export const useDeletePet = (props: UseDeletePetProps) => useMutate<void, Error, void, number>(\\"DELETE\\", \`/pets\`, { ...props });
export interface UpdatePetPathParams {
id: number
}
export type UpdatePetProps = Omit<MutateProps<Pet, Error, void, UpdatePetRequestRequestBody>, \\"path\\" | \\"verb\\"> & {id: number};
/**
Expand All @@ -175,12 +183,12 @@ export const UpdatePet = ({id, ...props}: UpdatePetProps) => (
/>
);
export type UseUpdatePetProps = Omit<UseMutateProps<Pet, void, UpdatePetRequestRequestBody>, \\"path\\" | \\"verb\\"> & {id: number};
export type UseUpdatePetProps = Omit<UseMutateProps<Pet, void, UpdatePetRequestRequestBody, UpdatePetPathParams>, \\"path\\" | \\"verb\\"> & UpdatePetPathParams;
/**
* Updates a pet in the store.
*/
export const useUpdatePet = ({id, ...props}: UseUpdatePetProps) => useMutate<Pet, Error, void, UpdatePetRequestRequestBody>(\\"PATCH\\", \`/pets/\${id}\`, props);
export const useUpdatePet = ({id, ...props}: UseUpdatePetProps) => useMutate<Pet, Error, void, UpdatePetRequestRequestBody>(\\"PATCH\\", ({ id }) => \`/pets/\${id}\`, { pathParams: { id }, ...props });
"
`;
Loading

0 comments on commit f50da00

Please sign in to comment.