openapi-codegen icon indicating copy to clipboard operation
openapi-codegen copied to clipboard

Config to change pattern of hook name

Open saschametz opened this issue 3 years ago • 2 comments

Great project! It's a huge time safer.

Is there a way to change the pattern of how the hook name is generated? I have the convention of adding Query or Mutation at the end of the hook name.

useSearchUsers -> useSearchUsersQuery useGistsCreateComment -> useGistsCreateCommentMutation

saschametz avatar Aug 26 '22 14:08 saschametz

Hey 👋

So far the component name is "hardcoded": https://github.com/fabien0102/openapi-codegen/blob/a12f12be1b4758dda1affe9096d724c15d760df5/plugins/typescript/src/generators/generateReactQueryComponents.ts#L204

But, good news, you can tweak the spec on the fly directly into the openapi-codegen.config.ts:

import {
  generateSchemaTypes,
  generateReactQueryComponents,
} from "@openapi-codegen/typescript";

import { defineConfig } from "@openapi-codegen/cli";

export default defineConfig({
  api: {
    from: {
      relativePath: "../server/openapi.yaml",
      source: "file",
    },
    outputDir: "src/api",
    to: async (context) => {
      // Add `Query` and `Mutation` suffix
      Object.values(context.openAPIDocument.paths).map((path) => {
        if (path.get) {
          path.get.operationId += "Query";
        }
        if (path.post) {
          path.post.operationId += "Mutation";
        }
        // TODO add other verbs
      });

      const filenamePrefix = "api";
      const { schemasFiles } = await generateSchemaTypes(context, {
        filenamePrefix,
      });
      await generateReactQueryComponents(context, {
        filenamePrefix,
        schemasFiles,
      });
    },
  },
});

A little helper will be nice for sure, but this should do the job for now 😉

fabien0102 avatar Aug 26 '22 14:08 fabien0102

Thank you for the example. It works perfectly 👍 I have extended it for the other methods:

const mutationMethods = ["post", "put", "patch", "delete"];
Object.values(context.openAPIDocument.paths).map((path) => {
  if (path.get) {
    path.get.operationId += "Query";
  }

  for (const method of mutationMethods) {
    if (!path[method]) continue;
    path[method].operationId += "Mutation";
  }
});

saschametz avatar Aug 27 '22 06:08 saschametz

@saschametz can we close this issue if you agree?

needim avatar Sep 23 '22 15:09 needim