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

Universal properties for arrays #2175

Merged
merged 14 commits into from
Nov 17, 2024
Merged
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
9 changes: 6 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@
- Both `logger` and `getChildLogger` arguments of `beforeRouting` function are replaced with all-purpose `getLogger`.
- Breaking changes to `createServer()` resolved return:
- Both `httpServer` and `httpsServer` are combined into single `servers` property (array, same order).
- Potentially breaking changes to `EndpointsFactory::build()` argument:
- Both `method` and `methods` made optional, can now be derived from `DependsOnMethod` or imply `GET` by default;
- When `methods` is used, it must be a non-empty array.
- Breaking changes to `EndpointsFactory::build()` argument:
- Plural `methods`, `tags` and `scopes` properties replaced with singular `method`, `tag`, `scope` accordingly;
- The `method` property also made optional and can now be derived from `DependsOnMethod` or imply `GET` by default;
- When `method` is assigned with an array, it must be non-empty.
- Breaking changes to `positive` and `negative` propeties of `ResultHandler` constructor argument:
- Plural `statusCodes` and `mimeTypes` props within the values are replaced with singular `statusCode` and `mimeType`.
- Other breaking changes:
- The `serializer` property of `Documentation` and `Integration` constructor argument removed;
- The `originalError` property of `InputValidationError` and `OutputValidationError` removed (use `cause` instead);
Expand Down
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ The endpoint responds with "Hello, World" or "Hello, {name}" if the name is supp
import { z } from "zod";

const helloWorldEndpoint = defaultEndpointsFactory.build({
// method: "get" (default) or methods: ["get", "post", ...]
// method: "get" (default) or array ["get", "post", ...]
input: z.object({
name: z.string().optional(),
}),
Expand Down Expand Up @@ -822,7 +822,7 @@ import {
const yourResultHandler = new ResultHandler({
positive: (data) => ({
schema: z.object({ data }),
mimeType: "application/json", // optinal, or mimeTypes for array
mimeType: "application/json", // optinal or array
}),
negative: z.object({ error: z.string() }),
handler: ({ error, input, output, request, response, logger }) => {
Expand Down Expand Up @@ -1095,7 +1095,7 @@ import { ResultHandler } from "express-zod-api";

new ResultHandler({
positive: (data) => ({
statusCodes: [201, 202], // created or will be created
statusCode: [201, 202], // created or will be created
schema: z.object({ status: z.literal("created"), data }),
}),
negative: [
Expand All @@ -1104,7 +1104,7 @@ new ResultHandler({
schema: z.object({ status: z.literal("exists"), id: z.number().int() }),
},
{
statusCodes: [400, 500], // validation or internal error
statusCode: [400, 500], // validation or internal error
schema: z.object({ status: z.literal("error"), reason: z.string() }),
},
],
Expand Down Expand Up @@ -1327,7 +1327,7 @@ const taggedEndpointsFactory = new EndpointsFactory({

const exampleEndpoint = taggedEndpointsFactory.build({
// ...
tag: "users", // or tags: ["users", "files"]
tag: "users", // or array ["users", "files"]
});
```

Expand Down Expand Up @@ -1405,7 +1405,7 @@ const output = z.object({
});

endpointsFactory.build({
methods,
method,
input,
output,
handler: async (): Promise<z.input<typeof output>> => ({
Expand Down
2 changes: 1 addition & 1 deletion example/endpoints/send-avatar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { readFile } from "node:fs/promises";

export const sendAvatarEndpoint = fileSendingEndpointsFactory.build({
shortDescription: "Sends a file content.",
tags: ["files", "users"],
tag: ["files", "users"],
input: z.object({
userId: z
.string()
Expand Down
2 changes: 1 addition & 1 deletion example/endpoints/stream-avatar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { fileStreamingEndpointsFactory } from "../factories";

export const streamAvatarEndpoint = fileStreamingEndpointsFactory.build({
shortDescription: "Streams a file content.",
tags: ["users", "files"],
tag: ["users", "files"],
input: z.object({
userId: z
.string()
Expand Down
4 changes: 2 additions & 2 deletions example/factories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export const statusDependingFactory = new EndpointsFactory({
config,
resultHandler: new ResultHandler({
positive: (data) => ({
statusCodes: [201, 202],
statusCode: [201, 202],
schema: z.object({ status: z.literal("created"), data }),
}),
negative: [
Expand All @@ -75,7 +75,7 @@ export const statusDependingFactory = new EndpointsFactory({
schema: z.object({ status: z.literal("exists"), id: z.number().int() }),
},
{
statusCodes: [400, 500],
statusCode: [400, 500],
schema: z.object({ status: z.literal("error"), reason: z.string() }),
},
],
Expand Down
33 changes: 12 additions & 21 deletions src/api-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,17 @@ export type ResponseVariant = keyof typeof defaultStatusCodes;

export interface ApiResponse<S extends z.ZodTypeAny> {
schema: S;
/**
* @default 200 for a positive response
* @default 400 for a negative response
* @override statusCodes
* */
statusCode?: number;
/**
* @default [200] for positive response
* @default [400] for negative response
* */
statusCodes?: [number, ...number[]];
/**
* @default "application/json"
* @override mimeTypes
* */
mimeType?: string;
/** @default [ "application/json" ] */
mimeTypes?: [string, ...string[]];
/** @default 200 for a positive and 400 for a negative response */
statusCode?: number | [number, ...number[]];
/** @default "application/json" */
mimeType?: string | [string, ...string[]];
/** @deprecated use statusCode */
statusCodes?: never;
/** @deprecated use mimeType */
mimeTypes?: never;
}

export type NormalizedResponse = Required<
Pick<ApiResponse<z.ZodTypeAny>, "schema" | "statusCodes" | "mimeTypes">
>;
export type NormalizedResponse = Pick<ApiResponse<z.ZodTypeAny>, "schema"> & {
statusCodes: Extract<ApiResponse<z.ZodTypeAny>["statusCode"], Array<unknown>>;
mimeTypes: Extract<ApiResponse<z.ZodTypeAny>["mimeType"], Array<unknown>>;
};
26 changes: 10 additions & 16 deletions src/endpoints-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,10 @@ type BuildProps<
description?: string;
shortDescription?: string;
operationId?: string | ((method: Method) => string);
} & ({ method?: Method } | { methods?: [Method, ...Method[]] }) &
({ scopes?: SCO[] } | { scope?: SCO }) &
({ tags?: TAG[] } | { tag?: TAG });
method?: Method | [Method, ...Method[]];
scope?: SCO | SCO[];
tag?: TAG | TAG[];
};

export class EndpointsFactory<
IN extends IOSchema<"strip"> = EmptySchema,
Expand Down Expand Up @@ -121,7 +122,9 @@ export class EndpointsFactory<
description,
shortDescription,
operationId,
...rest
scope,
tag,
method,
}: BuildProps<BIN, BOUT, IN, OUT, SCO, TAG>): Endpoint<
z.ZodIntersection<IN, BIN>,
BOUT,
Expand All @@ -130,20 +133,11 @@ export class EndpointsFactory<
TAG
> {
const { middlewares, resultHandler } = this;
const methods =
"method" in rest && rest.method
? [rest.method]
: ("methods" in rest && rest.methods) || undefined;
const methods = typeof method === "string" ? [method] : method;
const getOperationId =
typeof operationId === "function" ? operationId : () => operationId;
const scopes =
"scopes" in rest
? rest.scopes
: "scope" in rest && rest.scope
? [rest.scope]
: [];
const tags =
"tags" in rest ? rest.tags : "tag" in rest && rest.tag ? [rest.tag] : [];
const scopes = typeof scope === "string" ? [scope] : scope || [];
const tags = typeof tag === "string" ? [tag] : tag || [];
return new Endpoint({
handler,
middlewares,
Expand Down
108 changes: 79 additions & 29 deletions src/migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ const originalErrorPropName = "originalError";
const getStatusCodeFromErrorMethod = "getStatusCodeFromError";
const loggerPropName = "logger";
const getChildLoggerPropName = "getChildLogger";
const methodsPropName = "methods";
const tagsPropName = "tags";
const scopesPropName = "scopes";
const statusCodesPropName = "statusCodes";
const mimeTypesPropName = "mimeTypes";
const buildMethod = "build";
const resultHandlerClass = "ResultHandler";
const handlerMethod = "handler";

const changedProps = {
[serverPropName]: "http",
Expand All @@ -24,6 +32,11 @@ const changedProps = {
[originalErrorPropName]: "cause",
[loggerPropName]: "getLogger",
[getChildLoggerPropName]: "getLogger",
[methodsPropName]: "method",
[tagsPropName]: "tag",
[scopesPropName]: "scope",
[statusCodesPropName]: "statusCode",
[mimeTypesPropName]: "mimeType",
};

const changedMethods = {
Expand Down Expand Up @@ -114,6 +127,26 @@ const v21 = ESLintUtils.RuleCreator.withoutDocs({
}
},
[NT.CallExpression]: (node) => {
if (
node.callee.type === NT.MemberExpression &&
node.callee.property.type === NT.Identifier &&
node.callee.property.name === buildMethod &&
node.arguments.length === 1 &&
node.arguments[0].type === NT.ObjectExpression
) {
const changed = node.arguments[0].properties.filter(
propByName([methodsPropName, tagsPropName, scopesPropName] as const),
);
for (const prop of changed) {
const replacement = changedProps[prop.key.name];
ctx.report({
node: prop,
messageId: "change",
data: { subject: "property", from: prop.key.name, to: replacement },
fix: (fixer) => fixer.replaceText(prop.key, replacement),
});
}
}
if (node.callee.type !== NT.Identifier) return;
if (
node.callee.name === createConfigName &&
Expand Down Expand Up @@ -204,39 +237,56 @@ const v21 = ESLintUtils.RuleCreator.withoutDocs({
});
}
},
[`${NT.Property}[key.name="${beforeRoutingPropName}"] ${NT.ArrowFunctionExpression} ${NT.Identifier}[name="${loggerPropName}"]`]:
(node: TSESTree.Identifier) => {
const { parent } = node;
const isProp = isPropWithId(parent);
if (isProp && parent.value === node) return; // not for renames
const replacement = `${changedProps[node.name as keyof typeof changedProps]}${isProp ? "" : "()"}`;
ctx.report({
node,
messageId: "change",
data: {
subject: isProp ? "property" : "const",
from: node.name,
to: replacement,
},
fix: (fixer) => fixer.replaceText(node, replacement),
});
},
[`${NT.Property}[key.name="${beforeRoutingPropName}"] ${NT.ArrowFunctionExpression} ${NT.Identifier}[name="${getChildLoggerPropName}"]`]:
(node: TSESTree.Identifier) => {
const { parent } = node;
const isProp = isPropWithId(parent);
if (isProp && parent.value === node) return; // not for renames
[`${NT.Property}[key.name="${beforeRoutingPropName}"] ${NT.ArrowFunctionExpression} ` +
`${NT.Identifier}[name="${loggerPropName}"]`]: (
node: TSESTree.Identifier,
) => {
const { parent } = node;
const isProp = isPropWithId(parent);
if (isProp && parent.value === node) return; // not for renames
const replacement = `${changedProps[node.name as keyof typeof changedProps]}${isProp ? "" : "()"}`;
ctx.report({
node,
messageId: "change",
data: {
subject: isProp ? "property" : "const",
from: node.name,
to: replacement,
},
fix: (fixer) => fixer.replaceText(node, replacement),
});
},
[`${NT.Property}[key.name="${beforeRoutingPropName}"] ${NT.ArrowFunctionExpression} ` +
`${NT.Identifier}[name="${getChildLoggerPropName}"]`]: (
node: TSESTree.Identifier,
) => {
const { parent } = node;
const isProp = isPropWithId(parent);
if (isProp && parent.value === node) return; // not for renames
const replacement = changedProps[node.name as keyof typeof changedProps];
ctx.report({
node,
messageId: "change",
data: {
subject: isProp ? "property" : "method",
from: node.name,
to: replacement,
},
fix: (fixer) => fixer.replaceText(node, replacement),
});
},
[`${NT.NewExpression}[callee.name='${resultHandlerClass}'] > ${NT.ObjectExpression} > ` +
`${NT.Property}[key.name!='${handlerMethod}'] ` +
`${NT.Property}[key.name=/(${statusCodesPropName}|${mimeTypesPropName})/]`]:
(node: TSESTree.Property) => {
if (!isPropWithId(node)) return;
const replacement =
changedProps[node.name as keyof typeof changedProps];
changedProps[node.key.name as keyof typeof changedProps];
ctx.report({
node,
messageId: "change",
data: {
subject: isProp ? "property" : "method",
from: node.name,
to: replacement,
},
fix: (fixer) => fixer.replaceText(node, replacement),
data: { subject: "property", from: node.key.name, to: replacement },
fix: (fixer) => fixer.replaceText(node.key, replacement),
});
},
}),
Expand Down
18 changes: 10 additions & 8 deletions src/result-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,9 @@ export type ResultSchema<R extends Result> =
/** @throws ResultHandlerError when Result is an empty array */
export const normalize = <A extends unknown[]>(
subject: Result | LazyResult<Result, A>,
features: {
features: Omit<NormalizedResponse, "schema"> & {
variant: ResponseVariant;
arguments: A;
statusCodes: [number, ...number[]];
mimeTypes: [string, ...string[]];
},
): NormalizedResponse[] => {
if (typeof subject === "function")
Expand All @@ -33,12 +31,16 @@ export const normalize = <A extends unknown[]>(
);
}
return (Array.isArray(subject) ? subject : [subject]).map(
({ schema, statusCodes, statusCode, mimeTypes, mimeType }) => ({
({ schema, statusCode, mimeType }) => ({
schema,
statusCodes: statusCode
? [statusCode]
: statusCodes || features.statusCodes,
mimeTypes: mimeType ? [mimeType] : mimeTypes || features.mimeTypes,
statusCodes:
typeof statusCode === "number"
? [statusCode]
: statusCode || features.statusCodes,
mimeTypes:
typeof mimeType === "string"
? [mimeType]
: mimeType || features.mimeTypes,
}),
);
};
Expand Down
2 changes: 1 addition & 1 deletion tests/system/system.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ describe("App in production mode", async () => {
}),
})
.build({
methods: ["get", "post"],
method: ["get", "post"],
input: z.object({ something: z.string() }),
output: z.object({ anything: z.number().positive() }).passthrough(), // allow excessive keys
handler: async ({
Expand Down
Loading
Loading