refactor(core): Move some request DTOs to @n8n/api-types (no-changelog) (#10880)

This commit is contained in:
कारतोफ्फेलस्क्रिप्ट™
2024-09-20 21:14:06 +02:00
committed by GitHub
parent 583d3a7acb
commit 769ddfdd1d
35 changed files with 648 additions and 316 deletions

View File

@@ -2,7 +2,9 @@ import { GlobalConfig } from '@n8n/config';
import { Router } from 'express';
import type { Application, Request, Response, RequestHandler } from 'express';
import { rateLimit as expressRateLimit } from 'express-rate-limit';
import { ApplicationError } from 'n8n-workflow';
import { Container, Service } from 'typedi';
import type { ZodClass } from 'zod-class';
import { AuthService } from '@/auth/auth.service';
import { inProduction, RESPONSE_ERROR_MESSAGES } from '@/constants';
@@ -42,6 +44,7 @@ export const getRouteMetadata = (controllerClass: Controller, handlerName: Handl
let route = metadata.routes.get(handlerName);
if (!route) {
route = {} as RouteMetadata;
route.args = [];
metadata.routes.set(handlerName, route);
}
return route;
@@ -76,8 +79,31 @@ export class ControllerRegistry {
);
for (const [handlerName, route] of metadata.routes) {
const handler = async (req: Request, res: Response) =>
await controller[handlerName](req, res);
const argTypes = Reflect.getMetadata(
'design:paramtypes',
controller,
handlerName,
) as unknown[];
// eslint-disable-next-line @typescript-eslint/no-loop-func
const handler = async (req: Request, res: Response) => {
const args: unknown[] = [req, res];
for (let index = 0; index < route.args.length; index++) {
const arg = route.args[index];
if (!arg) continue; // Skip args without any decorators
if (arg.type === 'param') args.push(req.params[arg.key]);
else if (['body', 'query'].includes(arg.type)) {
const paramType = argTypes[index] as ZodClass;
if (paramType && 'parse' in paramType) {
const output = paramType.safeParse(req[arg.type]);
if (output.success) args.push(output.data);
else {
return res.status(400).json(output.error.errors[0]);
}
}
} else throw new ApplicationError('Unknown arg type: ' + arg.type);
}
return await controller[handlerName](...args);
};
router[route.method](
route.path,