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: implement function generation using useSWRMutation #1148

Merged

Conversation

soartec-lab
Copy link
Collaborator

@soartec-lab soartec-lab commented Jan 7, 2024

Status

READY

Description

fix #1013

Originally, in generateSwrHook, if verb was other than Verbs.GET, processing was skipped, but we implemented a function to generate a function using useSWRMutation.

Since the processing required for mutation is different from query, we have newly added generateSwrMutationImplementation, which is a function for generating the string of the function itself, and generateSwrMutationArguments, which generates arguments.
Also, since useSWRMutation requires a dedicated Fetcher as the second argument, I reused it by wrapping the http function. This allows reuse of mock and customization of http client using global mutator.

Related PRs

none

Todos

  • Tests
  • Documentation
  • Changelog Entry (unreleased)

Steps to Test or Reproduce

  1. Prepare an OpenAPI definition for petstore that defines mutation.
openapi: '3.0.0'
info:
  version: 1.0.0
  title: Swagger Petstore
  license:
    name: MIT
servers:
  - url: http://petstore.swagger.io/v1
paths:
  /pets:
    post:
      summary: Create a pet
      operationId: createPets
      tags:
        - pets
      requestBody:
        description: post body
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PetParams'
      responses:
        '201':
          description: Null response
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
  /pets/{petId}:
    patch:
      summary: Update for a specific pet
      operationId: updatePetByParams
      tags:
        - pets
      parameters:
        - name: petId
          in: path
          required: true
          description: The id of the pet to retrieve
          schema:
            type: string
      requestBody:
        description: post body
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PetParams'
      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:
    PetParams:
      type: object
      required:
        - name
      properties:
        name:
          type: string
        tag:
          type: string
    Pet:
      type: object
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        tag:
          type: string
    Error:
      type: object
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
  1. Prepare orval.config.js
module.exports = {
  'petstore-file': {
    input: {
      target: './petstore.yaml',
    },
    output: {
      mode: 'tags-split',
      client: 'swr',
      baseUrl: 'http://localhost:8000',
      target: 'src/gen/endpoints',
      schemas: 'src/gen/model',
    },
  },
};
  1. execute orval
orval
  1. generated custom hook

for example:

export const getCreatePetsMutationFetcher = (options?: AxiosRequestConfig) => {
  return (
    _: string,
    { arg }: { arg: Arguments },
  ): Promise<AxiosResponse<void>> => {
    return createPets(arg as PetParams, options);
  };
};
export const getCreatePetsMutationKey = () =>
  `http://localhost:8000/pets` as const;

export type CreatePetsMutationResult = NonNullable<
  Awaited<ReturnType<typeof createPets>>
>;
export type CreatePetsMutationError = AxiosError<Error>;

/**
 * @summary Create a pet
 */
export const useCreatePets = <TError = AxiosError<Error>>(options?: {
  swr?: SWRMutationConfiguration<
    Awaited<ReturnType<typeof createPets>>,
    TError,
    string,
    Arguments,
    Awaited<ReturnType<typeof createPets>>
  > & { swrKey?: string };
  axios?: AxiosRequestConfig;
}) => {
  const { swr: swrOptions, axios: axiosOptions } = options ?? {};

  const swrKey = swrOptions?.swrKey ?? getCreatePetsMutationKey();
  const swrFn = getCreatePetsMutationFetcher(axiosOptions);

  const query = useSWRMutation(swrKey, swrFn, swrOptions);

  return {
    swrKey,
    ...query,
  };
};

@melloware
Copy link
Collaborator

Looks good so far I see you are still working on the failing tests. Appreciate your effort on this!

@melloware melloware self-requested a review January 7, 2024 15:20
@melloware melloware added the enhancement New feature or request label Jan 7, 2024
@melloware melloware added this to the 6.24.0 milestone Jan 7, 2024
@soartec-lab
Copy link
Collaborator Author

Thank you for comment ✨ There are still some problems, I'll let you know when I fix them.

@soartec-lab soartec-lab force-pushed the feat/add-use-swr-muration-generator branch from 8129a9a to 59e64e2 Compare January 12, 2024 14:23
@soartec-lab soartec-lab marked this pull request as ready for review January 13, 2024 00:33
@soartec-lab
Copy link
Collaborator Author

@melloware @anymaniax
This PR is Ready 🙌 So could you review?

@melloware melloware merged commit 632a666 into anymaniax:master Jan 13, 2024
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

SWR: add useSwrMutation hook
2 participants