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

integrate ts-to-zod #217

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16,227 changes: 467 additions & 15,760 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions plugins/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"lodash": "^4.17.21",
"openapi3-ts": "^2.0.1",
"pluralize": "^8.0.0",
"ts-to-zod": "^3.8.3",
"tslib": "^2.3.1",
"tsutils": "^3.21.0",
"typescript": "4.8.2"
Expand Down
4 changes: 2 additions & 2 deletions plugins/typescript/src/core/createNamespaceImport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import { factory as f } from "typescript";
* @param filename path of the module
* @returns ts.Node of the import declaration
*/
export const createNamespaceImport = (namespace: string, filename: string) =>
export const createNamespaceImport = (namespace: string, filename: string, isTypeOnly = true) =>
f.createImportDeclaration(
undefined,
f.createImportClause(
true,
isTypeOnly,
undefined,
f.createNamespaceImport(f.createIdentifier(namespace))
),
Expand Down
6 changes: 6 additions & 0 deletions plugins/typescript/src/core/createOperationFetcherFnNodes.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { OperationObject } from "openapi3-ts";
import ts, { factory as f } from "typescript";
import { createZodValidatorResponse } from "../utils/zodHelper";
import { camelizedPathParams } from "./camelizedPathParams";

/**
Expand All @@ -20,6 +21,8 @@ export const createOperationFetcherFnNodes = ({
url,
verb,
name,
validateResponseWithZod,
printNodes,
}: {
dataType: ts.TypeNode;
errorType: ts.TypeNode;
Expand All @@ -33,6 +36,8 @@ export const createOperationFetcherFnNodes = ({
url: string;
verb: string;
name: string;
validateResponseWithZod: boolean;
printNodes: (nodes: ts.Node[]) => string;
}) => {
const nodes: ts.Node[] = [];
if (operation.description) {
Expand Down Expand Up @@ -119,6 +124,7 @@ export const createOperationFetcherFnNodes = ({
f.createIdentifier("signal")
),
]),
...(validateResponseWithZod ? createZodValidatorResponse(dataType, printNodes) : []),
],
false
),
Expand Down
26 changes: 18 additions & 8 deletions plugins/typescript/src/generators/generateFetchers.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
import ts, { factory as f } from "typescript";
import * as c from "case";
import { get } from "lodash";
import ts, { factory as f } from "typescript";

import { ConfigBase, Context } from "./types";
import { PathItemObject } from "openapi3-ts";
import { ConfigBase, Context } from "./types";

import { getUsedImports } from "../core/getUsedImports";
import { createWatermark } from "../core/createWatermark";
import { createNamedImport } from "../core/createNamedImport";
import { createOperationFetcherFnNodes } from "../core/createOperationFetcherFnNodes";
import { isVerb } from "../core/isVerb";
import { isOperationObject } from "../core/isOperationObject";
import { createWatermark } from "../core/createWatermark";
import { getOperationTypes } from "../core/getOperationTypes";
import { createNamedImport } from "../core/createNamedImport";
import { getUsedImports } from "../core/getUsedImports";
import { isOperationObject } from "../core/isOperationObject";
import { isVerb } from "../core/isVerb";

import { createNamespaceImport } from "../core/createNamespaceImport";
import { getFetcher } from "../templates/fetcher";
import { getUtils } from "../templates/utils";
import { createNamespaceImport } from "../core/createNamespaceImport";
import { createZodNamespaceImport } from "../utils/zodHelper";

export type Config = ConfigBase & {
/**
Expand All @@ -33,6 +34,12 @@ export type Config = ConfigBase & {
* This will mark the header as optional in the component API
*/
injectedHeaders?: string[];

zodFiles?: {
schemas: string;
inferredTypes: string;
integrationTests: string;
}
};

export const generateFetchers = async (context: Context, config: Config) => {
Expand Down Expand Up @@ -172,6 +179,8 @@ export const generateFetchers = async (context: Context, config: Config) => {
url: route,
verb,
name: operationId,
validateResponseWithZod: config.zodFiles !== undefined,
printNodes,
})
);
});
Expand Down Expand Up @@ -230,6 +239,7 @@ export const generateFetchers = async (context: Context, config: Config) => {
createWatermark(context.openAPIDocument.info),
createNamespaceImport("Fetcher", `./${fetcherFilename}`),
createNamedImport(fetcherImports, `./${fetcherFilename}`),
...createZodNamespaceImport(config.zodFiles?.schemas),
...usedImportsNodes,
...nodes,
])
Expand Down
90 changes: 50 additions & 40 deletions plugins/typescript/src/generators/generateReactQueryComponents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { createNamedImport } from "../core/createNamedImport";
import { getFetcher } from "../templates/fetcher";
import { getContext } from "../templates/context";
import { getUtils } from "../templates/utils";
import { createZodNamespaceImport } from "../utils/zodHelper";
import { createNamespaceImport } from "../core/createNamespaceImport";
import { camelizedPathParams } from "../core/camelizedPathParams";

Expand All @@ -35,6 +36,12 @@ export type Config = ConfigBase & {
* This will mark the header as optional in the component API
*/
injectedHeaders?: string[];

zodFiles?: {
schemas: string;
inferredTypes: string;
integrationTests: string;
}
};

export const generateReactQueryComponents = async (
Expand All @@ -58,9 +65,9 @@ export const generateReactQueryComponents = async (
return (
printer.printNode(ts.EmitHint.Unspecified, node, sourceFile) +
(ts.isJSDoc(node) ||
(ts.isImportDeclaration(node) &&
nodes[i + 1] &&
ts.isImportDeclaration(nodes[i + 1]))
(ts.isImportDeclaration(node) &&
nodes[i + 1] &&
ts.isImportDeclaration(nodes[i + 1]))
? ""
: "\n")
);
Expand Down Expand Up @@ -195,28 +202,30 @@ export const generateReactQueryComponents = async (
url: route,
verb,
name: operationFetcherFnName,
validateResponseWithZod: config.zodFiles !== undefined,
printNodes,
}),
...(component === "useQuery"
? createQueryHook({
operationFetcherFnName,
operation,
dataType,
errorType,
variablesType,
contextHookName,
name: `use${c.pascal(operationId)}`,
operationId,
url: route,
})
operationFetcherFnName,
operation,
dataType,
errorType,
variablesType,
contextHookName,
name: `use${c.pascal(operationId)}`,
operationId,
url: route,
})
: createMutationHook({
operationFetcherFnName,
operation,
dataType,
errorType,
variablesType,
contextHookName,
name: `use${c.pascal(operationId)}`,
}))
operationFetcherFnName,
operation,
dataType,
errorType,
variablesType,
contextHookName,
name: `use${c.pascal(operationId)}`,
}))
);
});
}
Expand All @@ -232,25 +241,25 @@ export const generateReactQueryComponents = async (
keyManagerItems.length > 0
? f.createUnionTypeNode(keyManagerItems)
: f.createTypeLiteralNode([
f.createPropertySignature(
undefined,
f.createIdentifier("path"),
undefined,
f.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)
),
f.createPropertySignature(
undefined,
f.createIdentifier("operationId"),
undefined,
f.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword)
),
f.createPropertySignature(
undefined,
f.createIdentifier("variables"),
undefined,
f.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword)
),
])
f.createPropertySignature(
undefined,
f.createIdentifier("path"),
undefined,
f.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)
),
f.createPropertySignature(
undefined,
f.createIdentifier("operationId"),
undefined,
f.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword)
),
f.createPropertySignature(
undefined,
f.createIdentifier("variables"),
undefined,
f.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword)
),
])
);

const { nodes: usedImportsNodes, keys: usedImportsKeys } = getUsedImports(
Expand All @@ -276,6 +285,7 @@ export const generateReactQueryComponents = async (
),
createNamespaceImport("Fetcher", `./${fetcherFilename}`),
createNamedImport(fetcherFn, `./${fetcherFilename}`),
...createZodNamespaceImport(config.zodFiles?.schemas),
...usedImportsNodes,
...nodes,
queryKeyManager,
Expand Down
10 changes: 10 additions & 0 deletions plugins/typescript/src/generators/generateReactQueryFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { getFetcher } from "../templates/fetcher";
import { getContext } from "../templates/context";
import { getUtils } from "../templates/utils";
import { createNamespaceImport } from "../core/createNamespaceImport";
import { createZodNamespaceImport } from "../utils/zodHelper";
import { camelizedPathParams } from "../core/camelizedPathParams";

export type Config = ConfigBase & {
Expand All @@ -37,6 +38,12 @@ export type Config = ConfigBase & {
* This will mark the header as optional in the component API
*/
injectedHeaders?: string[];

zodFiles?: {
schemas: string;
inferredTypes: string;
integrationTests: string;
}
};

export const generateReactQueryFunctions = async (
Expand Down Expand Up @@ -196,6 +203,8 @@ export const generateReactQueryFunctions = async (
url: route,
verb,
name: operationFetcherFnName,
validateResponseWithZod: config.zodFiles !== undefined,
printNodes,
}),
...createOperationQueryFnNodes({
operationFetcherFnName,
Expand Down Expand Up @@ -273,6 +282,7 @@ export const generateReactQueryFunctions = async (
),
createNamespaceImport("Fetcher", `./${fetcherFilename}`),
createNamedImport(fetcherFn, `./${fetcherFilename}`),
...createZodNamespaceImport(config.zodFiles?.schemas),
...usedImportsNodes,
...nodes,
queryKeyManager,
Expand Down
52 changes: 52 additions & 0 deletions plugins/typescript/src/generators/generateZod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import * as c from "case";
import { GenerateProps, generate } from "ts-to-zod";
import { ConfigBase, Context } from "../generators/types";

export type Config = ConfigBase & {
/**
* Generated files paths from `generateSchemaTypes`
*/
schemasFiles: {
requestBodies: string;
schemas: string;
parameters: string;
responses: string;
};
generateProps?: GenerateProps;
writeInferredTypes?: boolean
writeIntegrationTests?: boolean
};

export const generateZod = async (context: Context, config: Config) => {
const result = generate({
sourceText: await context.readFile(config.schemasFiles.schemas + ".ts"),
...config.generateProps,
})

const filenamePrefix =
c.snake(config.filenamePrefix ?? context.openAPIDocument.info.title) + "-";

const formatFilename = config.filenameCase ? c[config.filenameCase] : c.camel;

const zodFiles = {
schemas: formatFilename(filenamePrefix + "-zod-schemas"),
inferredTypes: formatFilename(filenamePrefix + "-zod-inferred-types"),
integrationTests: formatFilename(filenamePrefix + "-zod-integration-tests"),
}

if (result.errors.length === 0) {
await context.writeFile(zodFiles.schemas + ".ts", result.getZodSchemasFile("./" + config.schemasFiles.schemas));

if (config.writeInferredTypes !== false) {
await context.writeFile(zodFiles.inferredTypes + ".ts", result.getInferredTypes("./" + zodFiles.schemas));

if (config.writeIntegrationTests !== false) {
await context.writeFile(zodFiles.integrationTests + ".ts", result.getIntegrationTestFile("./" + zodFiles.inferredTypes, "./" + zodFiles.schemas));
}
}
} else {
console.log(`⚠️ Zod Generate finished with errors!`, result.errors);
}

return zodFiles
}
1 change: 1 addition & 0 deletions plugins/typescript/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export { generateSchemaTypes } from "./generators/generateSchemaTypes";
export { generateReactQueryComponents } from "./generators/generateReactQueryComponents";
export { generateReactQueryFunctions } from "./generators/generateReactQueryFunctions";
export { generateFetchers } from "./generators/generateFetchers";
export { generateZod } from "./generators/generateZod";

// Utils
export { renameComponent } from "./utils/renameComponent";
Expand Down
4 changes: 4 additions & 0 deletions plugins/typescript/src/templates/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ export const getContext = (prefix: string, componentsFile: string) =>
* Query params to inject in the fetcher
*/
queryParams?: {};
/**
* Enable response validation
*/
responseValidatorEnabled?: boolean
};
queryOptions: {
/**
Expand Down
Loading