Skip to content

Commit

Permalink
chore: format output source files
Browse files Browse the repository at this point in the history
We now format the generated hooks file to remove unused imports and fix some formatting issues.
  • Loading branch information
seriouslag committed Apr 23, 2024
1 parent 751c6ed commit 6c2d13f
Show file tree
Hide file tree
Showing 8 changed files with 73 additions and 47 deletions.
8 changes: 6 additions & 2 deletions src/common.mts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
ClassDeclaration,
} from "ts-morph";
import { LimitedUserConfig } from "./cli.mjs";
import { requestsOutputPath } from "./constants.mjs";
import { queriesOutputPath, requestsOutputPath } from "./constants.mjs";

export const TData = ts.factory.createIdentifier("TData");
export const TError = ts.factory.createIdentifier("TError");
Expand Down Expand Up @@ -163,6 +163,10 @@ export function formatOptions(options: LimitedUserConfig) {
return formattedOptions;
}

export function buildOutputPath(outputPath: string) {
export function buildRequestsOutputPath(outputPath: string) {
return path.join(outputPath, requestsOutputPath);
}

export function buildQueriesOutputPath(outputPath: string) {
return path.join(outputPath, queriesOutputPath);
}
20 changes: 1 addition & 19 deletions src/createImports.mts
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,14 @@ export const createImports = ({
.getSourceFiles()
.find((sourceFile) => sourceFile.getFilePath().includes(modalsFileName));

const serviceFile = project
.getSourceFiles()
.find((sourceFile) => sourceFile.getFilePath().includes(serviceFileName));
const serviceFile = project.getSourceFileOrThrow(`${serviceFileName}.ts`);

if (!modelsFile) {
console.warn(`
⚠️ WARNING: No models file found.
This may be an error if \`.components.schemas\` or \`.components.parameters\` is defined in your OpenAPI input.`);
}

if (!serviceFile) {
throw new Error("No service file found");
}

const modelNames = modelsFile
? Array.from(modelsFile.getExportedDeclarations().keys())
: [];
Expand All @@ -42,10 +36,6 @@ export const createImports = ({
name.endsWith(serviceEndName)
);

const serviceNamesData = serviceExports.filter((name) =>
name.endsWith("Data")
);

const imports = [
ts.factory.createImportDeclaration(
undefined,
Expand Down Expand Up @@ -107,14 +97,6 @@ export const createImports = ({
ts.factory.createIdentifier(serviceName)
)
),
// import all data objects from service file
...serviceNamesData.map((dataName) =>
ts.factory.createImportSpecifier(
false,
undefined,
ts.factory.createIdentifier(dataName)
)
),
])
),
ts.factory.createStringLiteral(join("../requests", serviceFileName)),
Expand Down
10 changes: 6 additions & 4 deletions src/createSource.mts
Original file line number Diff line number Diff line change
Expand Up @@ -132,20 +132,22 @@ export const createSource = async ({
const { commonSource, mainSource, suspenseSource, indexSource } =
await createSourceFile(outputPath, serviceEndName);

const comment = `// generated with @7nohe/openapi-react-query-codegen@${version} \n\n`;

const commonResult =
`// generated with @7nohe/openapi-react-query-codegen@${version} \n` +
comment +
printer.printNode(ts.EmitHint.Unspecified, commonSource, commonFile);

const mainResult =
`// generated with @7nohe/openapi-react-query-codegen@${version} \n` +
comment +
printer.printNode(ts.EmitHint.Unspecified, mainSource, queriesFile);

const suspenseResult =
`// generated with @7nohe/openapi-react-query-codegen@${version} \n` +
comment +
printer.printNode(ts.EmitHint.Unspecified, suspenseSource, suspenseFile);

const indexResult =
`// generated with @7nohe/openapi-react-query-codegen@${version} \n` +
comment +
printer.printNode(ts.EmitHint.Unspecified, indexSource, indexFile);

return [
Expand Down
25 changes: 25 additions & 0 deletions src/format.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { IndentationText, NewLineKind, Project, QuoteKind } from "ts-morph";

export const formatOutput = async (outputPath: string) => {
const project = new Project({
skipAddingFilesFromTsConfig: true,
manipulationSettings: {
indentationText: IndentationText.TwoSpaces,
newLineKind: NewLineKind.LineFeed,
quoteKind: QuoteKind.Double,
usePrefixAndSuffixTextForRename: false,
useTrailingCommas: true,
},
});

const sourceFiles = project.addSourceFilesAtPaths(`${outputPath}/**/*`);

const tasks = sourceFiles.map((sourceFile) => {
sourceFile.formatText();
sourceFile.fixMissingImports();
sourceFile.organizeImports();
return sourceFile.save();
});

await Promise.all(tasks);
};
11 changes: 9 additions & 2 deletions src/generate.mts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { createClient, UserConfig } from "@hey-api/openapi-ts";
import { print } from "./print.mjs";
import { createSource } from "./createSource.mjs";
import { buildOutputPath, formatOptions } from "./common.mjs";
import {
buildQueriesOutputPath,
buildRequestsOutputPath,
formatOptions,
} from "./common.mjs";
import { LimitedUserConfig } from "./cli.mjs";
import { formatOutput } from "./format.mjs";

export async function generate(options: LimitedUserConfig, version: string) {
const openApiOutputPath = buildOutputPath(options.output);
const openApiOutputPath = buildRequestsOutputPath(options.output);
const formattedOptions = formatOptions(options);

const config: UserConfig = {
Expand Down Expand Up @@ -41,4 +46,6 @@ export async function generate(options: LimitedUserConfig, version: string) {
serviceEndName: "Service", // we are hard coding this because changing the service end name was depreciated in @hey-api/openapi-ts
});
await print(source, formattedOptions);
const queriesOutputPath = buildQueriesOutputPath(options.output);
await formatOutput(queriesOutputPath);
}
4 changes: 2 additions & 2 deletions src/print.mts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { mkdir, writeFile } from "fs/promises";
import path from "path";
import { queriesOutputPath } from "./constants.mjs";
import { LimitedUserConfig } from "./cli.mjs";
import { exists } from "./common.mjs";
import { buildQueriesOutputPath, exists } from "./common.mjs";

async function printGeneratedTS(
result: {
Expand All @@ -11,7 +11,7 @@ async function printGeneratedTS(
},
options: Pick<LimitedUserConfig, "output">
) {
const dir = path.join(options.output, queriesOutputPath);
const dir = buildQueriesOutputPath(options.output);
const dirExists = await exists(dir);
if (!dirExists) {
await mkdir(dir, { recursive: true });
Expand Down
4 changes: 4 additions & 0 deletions tests/__snapshots__/createSource.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

exports[`createSource > createSource 1`] = `
"// generated with @7nohe/[email protected]
export * from "./common";
export * from "./queries";
"
`;

exports[`createSource > createSource 2`] = `
"// generated with @7nohe/[email protected]
import { useQuery, useSuspenseQuery, useMutation, UseQueryResult, UseQueryOptions, UseMutationOptions, UseMutationResult } from "@tanstack/react-query";
import { DefaultService } from "../requests/services.gen";
import { Pet, NewPet, Error, $OpenApiTs } from "../requests/types.gen";
Expand All @@ -29,6 +31,7 @@ export type DefaultServiceDeletePetMutationResult = Awaited<ReturnType<typeof De
exports[`createSource > createSource 3`] = `
"// generated with @7nohe/[email protected]
import * as Common from "./common";
import { useQuery, useSuspenseQuery, useMutation, UseQueryResult, UseQueryOptions, UseMutationOptions, UseMutationResult } from "@tanstack/react-query";
import { DefaultService } from "../requests/services.gen";
Expand Down Expand Up @@ -106,6 +109,7 @@ export const useDefaultServiceDeletePet = <TData = Common.DefaultServiceDeletePe
exports[`createSource > createSource 4`] = `
"// generated with @7nohe/[email protected]
import * as Common from "./common";
import { useQuery, useSuspenseQuery, useMutation, UseQueryResult, UseQueryOptions, UseMutationOptions, UseMutationResult } from "@tanstack/react-query";
import { DefaultService } from "../requests/services.gen";
Expand Down
38 changes: 20 additions & 18 deletions tests/__snapshots__/generate.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

exports[`generate > common.ts 1`] = `
"// generated with @7nohe/[email protected]
import { useQuery, useSuspenseQuery, useMutation, UseQueryResult, UseQueryOptions, UseMutationOptions, UseMutationResult } from "@tanstack/react-query";
import { UseQueryResult } from "@tanstack/react-query";
import { DefaultService } from "../requests/services.gen";
import { Pet, NewPet, Error, $OpenApiTs } from "../requests/types.gen";
export type DefaultServiceFindPetsDefaultResponse = Awaited<ReturnType<typeof DefaultService.findPets>>;
export type DefaultServiceFindPetsQueryResult<TData = DefaultServiceFindPetsDefaultResponse, TError = unknown> = UseQueryResult<TData, TError>;
export const useDefaultServiceFindPetsKey = "DefaultServiceFindPets";
Expand All @@ -22,17 +22,19 @@ export type DefaultServiceDeletePetMutationResult = Awaited<ReturnType<typeof De
exports[`generate > index.ts 1`] = `
"// generated with @7nohe/[email protected]
export * from "./common";
export * from "./queries";
"
`;
exports[`generate > queries.ts 1`] = `
"// generated with @7nohe/[email protected]
import * as Common from "./common";
import { useQuery, useSuspenseQuery, useMutation, UseQueryResult, UseQueryOptions, UseMutationOptions, UseMutationResult } from "@tanstack/react-query";
import { UseMutationOptions, UseQueryOptions, useMutation, useQuery } from "@tanstack/react-query";
import { DefaultService } from "../requests/services.gen";
import { Pet, NewPet, Error, $OpenApiTs } from "../requests/types.gen";
import { NewPet } from "../requests/types.gen";
import * as Common from "./common";
/**
* Returns all pets from the system that the user has access to
* Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.
Expand All @@ -47,8 +49,8 @@ import { Pet, NewPet, Error, $OpenApiTs } from "../requests/types.gen";
* @throws ApiError
*/
export const useDefaultServiceFindPets = <TData = Common.DefaultServiceFindPetsDefaultResponse, TError = unknown, TQueryKey extends Array<unknown> = unknown[]>({ limit, tags }: {
limit?: number;
tags?: string[];
limit?: number;
tags?: string[];
} = {}, queryKey?: TQueryKey, options?: Omit<UseQueryOptions<TData, TError>, "queryKey" | "queryFn">) => useQuery<TData, TError>({ queryKey: [Common.useDefaultServiceFindPetsKey, ...(queryKey ?? [{ limit, tags }])], queryFn: () => DefaultService.findPets({ limit, tags }) as TData, ...options });
/**
* @deprecated
Expand All @@ -66,7 +68,7 @@ export const useDefaultServiceGetNotDefined = <TData = Common.DefaultServiceGetN
* @throws ApiError
*/
export const useDefaultServiceFindPetById = <TData = Common.DefaultServiceFindPetByIdDefaultResponse, TError = unknown, TQueryKey extends Array<unknown> = unknown[]>({ id }: {
id: number;
id: number;
}, queryKey?: TQueryKey, options?: Omit<UseQueryOptions<TData, TError>, "queryKey" | "queryFn">) => useQuery<TData, TError>({ queryKey: [Common.useDefaultServiceFindPetByIdKey, ...(queryKey ?? [{ id }])], queryFn: () => DefaultService.findPetById({ id }) as TData, ...options });
/**
* Creates a new pet in the store. Duplicates are allowed
Expand All @@ -77,9 +79,9 @@ export const useDefaultServiceFindPetById = <TData = Common.DefaultServiceFindPe
* @throws ApiError
*/
export const useDefaultServiceAddPet = <TData = Common.DefaultServiceAddPetMutationResult, TError = unknown, TContext = unknown>(options?: Omit<UseMutationOptions<TData, TError, {
requestBody: NewPet;
requestBody: NewPet;
}, TContext>, "mutationFn">) => useMutation<TData, TError, {
requestBody: NewPet;
requestBody: NewPet;
}, TContext>({ mutationFn: ({ requestBody }) => DefaultService.addPet({ requestBody }) as unknown as Promise<TData>, ...options });
/**
* @deprecated
Expand All @@ -97,19 +99,19 @@ export const useDefaultServicePostNotDefined = <TData = Common.DefaultServicePos
* @throws ApiError
*/
export const useDefaultServiceDeletePet = <TData = Common.DefaultServiceDeletePetMutationResult, TError = unknown, TContext = unknown>(options?: Omit<UseMutationOptions<TData, TError, {
id: number;
id: number;
}, TContext>, "mutationFn">) => useMutation<TData, TError, {
id: number;
id: number;
}, TContext>({ mutationFn: ({ id }) => DefaultService.deletePet({ id }) as unknown as Promise<TData>, ...options });
"
`;
exports[`generate > suspense.ts 1`] = `
"// generated with @7nohe/[email protected]
import * as Common from "./common";
import { useQuery, useSuspenseQuery, useMutation, UseQueryResult, UseQueryOptions, UseMutationOptions, UseMutationResult } from "@tanstack/react-query";
import { UseQueryOptions, useSuspenseQuery } from "@tanstack/react-query";
import { DefaultService } from "../requests/services.gen";
import { Pet, NewPet, Error, $OpenApiTs } from "../requests/types.gen";
import * as Common from "./common";
/**
* Returns all pets from the system that the user has access to
* Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.
Expand All @@ -124,8 +126,8 @@ import { Pet, NewPet, Error, $OpenApiTs } from "../requests/types.gen";
* @throws ApiError
*/
export const useDefaultServiceFindPetsSuspense = <TData = Common.DefaultServiceFindPetsDefaultResponse, TError = unknown, TQueryKey extends Array<unknown> = unknown[]>({ limit, tags }: {
limit?: number;
tags?: string[];
limit?: number;
tags?: string[];
} = {}, queryKey?: TQueryKey, options?: Omit<UseQueryOptions<TData, TError>, "queryKey" | "queryFn">) => useSuspenseQuery<TData, TError>({ queryKey: [Common.useDefaultServiceFindPetsKey, ...(queryKey ?? [{ limit, tags }])], queryFn: () => DefaultService.findPets({ limit, tags }) as TData, ...options });
/**
* @deprecated
Expand All @@ -143,7 +145,7 @@ export const useDefaultServiceGetNotDefinedSuspense = <TData = Common.DefaultSer
* @throws ApiError
*/
export const useDefaultServiceFindPetByIdSuspense = <TData = Common.DefaultServiceFindPetByIdDefaultResponse, TError = unknown, TQueryKey extends Array<unknown> = unknown[]>({ id }: {
id: number;
id: number;
}, queryKey?: TQueryKey, options?: Omit<UseQueryOptions<TData, TError>, "queryKey" | "queryFn">) => useSuspenseQuery<TData, TError>({ queryKey: [Common.useDefaultServiceFindPetByIdKey, ...(queryKey ?? [{ id }])], queryFn: () => DefaultService.findPetById({ id }) as TData, ...options });
"
`;

0 comments on commit 6c2d13f

Please sign in to comment.