Files
outline/server/middlewares/validate.ts
Tom Moor bf45e97641 chore: Enforce type import consistency (#10968)
* Update types

* fix circular dep

* type imports

* lint type imports and --fix
2025-12-19 23:07:02 -05:00

26 lines
777 B
TypeScript

import type { Next } from "koa";
import type { z } from "zod";
import { ZodError } from "zod";
import { ValidationError } from "@server/errors";
import type { APIContext, BaseReq } from "@server/types";
export default function validate<T extends z.ZodType<BaseReq>>(schema: T) {
return async function validateMiddleware(ctx: APIContext, next: Next) {
try {
ctx.input = {
...(ctx.input ?? {}),
...schema.parse(ctx.request),
};
} catch (err) {
if (err instanceof ZodError) {
const { path, message } = err.issues[0];
const errMessage =
path.length > 0 ? `${path[path.length - 1]}: ${message}` : message;
throw ValidationError(errMessage);
}
ctx.throw(err);
}
return next();
};
}