Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
31 changes: 21 additions & 10 deletions express-zod-api/src/common-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@ import { z } from "zod/v4";
import type { $ZodTransform, $ZodType } from "zod/v4/core";
import { CommonConfig, InputSource, InputSources } from "./config-type";
import { contentTypes } from "./content-type";
import { AuxMethod, ClientMethod, Method } from "./method";
import {
ClientMethod,
SomeMethod,
isMethod,
Method,
CORSMethod,
} from "./method";
import { ResponseVariant } from "./api-response";

/** @desc this type does not allow props assignment, but it works for reading them when merged with another interface */
Expand Down Expand Up @@ -43,21 +49,26 @@ export const defaultInputSources: InputSources = {
patch: ["body", "params"],
delete: ["query", "params"],
};
const fallbackInputSource: InputSource[] = ["body", "query", "params"];
const fallbackInputSources: InputSource[] = ["body", "query", "params"];

/** @todo consider removing "as" to ensure more constraints and realistic handling */
export const getActualMethod = (request: Request) =>
request.method.toLowerCase() as Method | AuxMethod;
request.method.toLowerCase() as SomeMethod;

export const getInputSources = (
actualMethod: ReturnType<typeof getActualMethod>,
actualMethod: SomeMethod,
userDefined: CommonConfig["inputSources"] = {},
) => {
if (actualMethod === "options") return [];
const method = actualMethod === "head" ? "get" : actualMethod;
return (
userDefined[method] || defaultInputSources[method] || fallbackInputSource
);
if (actualMethod === ("options" satisfies CORSMethod)) return [];
const method =
actualMethod === ("head" satisfies ClientMethod)
? ("get" satisfies Method)
: isMethod(actualMethod)
? actualMethod
: undefined;
const matchingSources = method
? userDefined[method] || defaultInputSources[method]
: undefined;
return matchingSources || fallbackInputSources;
};

export const getInput = (
Expand Down
13 changes: 9 additions & 4 deletions express-zod-api/src/endpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { lastResortHandler } from "./last-resort";
import { ActualLogger } from "./logger-helpers";
import { LogicalContainer } from "./logical-container";
import { getBrand, getExamples } from "./metadata";
import { AuxMethod, ClientMethod, Method } from "./method";
import { ClientMethod, CORSMethod, Method, SomeMethod } from "./method";
import { AbstractMiddleware, ExpressMiddleware } from "./middleware";
import { ContentType } from "./content-type";
import { ezRawBrand } from "./raw-schema";
Expand Down Expand Up @@ -213,15 +213,19 @@ export class Endpoint<
response,
...rest
}: {
method: Method | AuxMethod;
method: SomeMethod;
input: Readonly<FlatObject>; // Issue #673: input is immutable, since this.inputSchema is combined with ones of middlewares
request: Request;
response: Response;
logger: ActualLogger;
options: Partial<OPT>;
}) {
for (const mw of this.#def.middlewares || []) {
if (method === "options" && !(mw instanceof ExpressMiddleware)) continue;
if (
method === ("options" satisfies CORSMethod) &&
!(mw instanceof ExpressMiddleware)
)
continue;
Object.assign(
options,
await mw.execute({ ...rest, options, response, logger }),
Expand Down Expand Up @@ -302,7 +306,8 @@ export class Endpoint<
options,
});
if (response.writableEnded) return;
if (method === "options") return void response.status(200).end();
if (method === ("options" satisfies CORSMethod))
return void response.status(200).end();
result = {
output: await this.#parseOutput(
await this.#parseAndRunHandler({
Expand Down
35 changes: 23 additions & 12 deletions express-zod-api/src/method.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,46 @@
import type { IRouter } from "express";

export type SomeMethod = Lowercase<string>;

type FamiliarMethod = Exclude<
keyof IRouter,
"param" | "use" | "route" | "stack"
>;

export const methods = [
"get",
"post",
"put",
"delete",
"patch",
] satisfies Array<keyof IRouter>;
] satisfies Array<FamiliarMethod>;

export const clientMethods = [
...methods,
"head",
] satisfies Array<FamiliarMethod>;

/**
* @desc Methods supported by the framework API to produce Endpoints on EndpointsFactory.
* @see BuildProps
* @example "get" | "post" | "put" | "delete" | "patch"
* */
export type Method = (typeof methods)[number];

/**
* @desc Additional methods having some technical handling in the framework
* @see makeCorsHeaders
* @todo consider removing it and introducing CORSMethod = ClientMethod | "options"
* */
export type AuxMethod = Extract<keyof IRouter, "options" | "head">;

export const clientMethods = [...methods, "head"] satisfies Array<
Method | Extract<AuxMethod, "head">
>;

/**
* @desc Methods usable on the client side, available via generated Integration and Documentation
* @see withHead
* @example Method | "head"
* */
export type ClientMethod = (typeof clientMethods)[number];

/**
* @desc Methods supported in CORS headers
* @see makeCorsHeaders
* @see createWrongMethodHandler
* @example ClientMethod | "options"
* */
export type CORSMethod = ClientMethod | Extract<FamiliarMethod, "options">;

export const isMethod = (subject: string): subject is Method =>
(methods as string[]).includes(subject);
10 changes: 5 additions & 5 deletions express-zod-api/src/routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ContentType } from "./content-type";
import { DependsOnMethod } from "./depends-on-method";
import { Diagnostics } from "./diagnostics";
import { AbstractEndpoint } from "./endpoint";
import { AuxMethod, isMethod, Method } from "./method";
import { CORSMethod, isMethod } from "./method";
import { OnEndpoint, walkRouting } from "./routing-walker";
import { ServeStatic } from "./serve-static";
import { GetLogger } from "./server-helpers";
Expand All @@ -24,15 +24,15 @@ export interface Routing {

export type Parsers = Partial<Record<ContentType, RequestHandler[]>>;

const lineUp = (methods: Array<Method | AuxMethod>) =>
const lineUp = (methods: CORSMethod[]) =>
methods // auxiliary methods go last
.sort((a, b) => +isMethod(b) - +isMethod(a) || a.localeCompare(b))
.join(", ")
.toUpperCase();

/** @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 */
export const createWrongMethodHandler =
(allowedMethods: Array<Method | AuxMethod>): RequestHandler =>
(allowedMethods: CORSMethod[]): RequestHandler =>
({ method }, res, next) => {
const Allow = lineUp(allowedMethods);
res.set({ Allow }); // in case of a custom errorHandler configured that does not care about headers in error
Expand All @@ -42,13 +42,13 @@ export const createWrongMethodHandler =
next(error);
};

const makeCorsHeaders = (accessMethods: Array<Method | AuxMethod>) => ({
const makeCorsHeaders = (accessMethods: CORSMethod[]) => ({
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": lineUp(accessMethods),
"Access-Control-Allow-Headers": "content-type",
});

type Siblings = Map<Method | AuxMethod, [RequestHandler[], AbstractEndpoint]>;
type Siblings = Map<CORSMethod, [RequestHandler[], AbstractEndpoint]>;

export const initRouting = ({
app,
Expand Down
10 changes: 0 additions & 10 deletions express-zod-api/tests/method.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ import {
isMethod,
methods,
Method,
AuxMethod,
clientMethods,
ClientMethod,
} from "../src/method";
import { describe } from "node:test";

describe("Method", () => {
describe("methods array", () => {
Expand Down Expand Up @@ -52,14 +50,6 @@ describe("Method", () => {
});
});

describe("AuxMethod", () => {
test("should be options or head", () => {
expectTypeOf<"options">().toExtend<AuxMethod>();
expectTypeOf<"head">().toExtend<AuxMethod>();
expectTypeOf<"other">().not.toExtend<AuxMethod>();
});
});

describe("isMethod", () => {
test.each(methods)("should validate %s", (one) => {
expect(isMethod(one)).toBe(true);
Expand Down