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

Глаза дракона #9

Merged
merged 3 commits into from
Oct 27, 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
41 changes: 41 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"@typegoose/typegoose": "12.8.0",
"chalk": "^5.3.0",
"class-transformer": "0.5.1",
"class-validator": "0.14.1",
"convict": "6.2.4",
"convict-format-with-validator": "6.2.0",
"dayjs": "1.11.13",
Expand Down
2 changes: 1 addition & 1 deletion src/cli/commands/import.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export class ImportCommand implements Command {
preview: offer.preview,
photos: offer.photos,
isPremium: offer.isPremium,
rating: offer.rating,
// rating: offer.rating,
housingType: offer.housingType,
roomsNumber: offer.roomsNumber,
guestsNumber: offer.guestsNumber,
Expand Down
6 changes: 2 additions & 4 deletions src/shared/helpers/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ export function fillDTO<T, V>(someDto: ClassConstructor<T>, plainObject: V) {
});
}

export function createErrorObject(message: string) {
return {
error: message,
};
export function createErrorObject(error: string) {
return { error };
}
22 changes: 19 additions & 3 deletions src/shared/libs/rest/controller/base-controller.abstract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { Response, Router } from 'express';
import { Logger } from '../../logger/index.js';
import { Route } from '../types/route.interface.js';
import { StatusCodes } from 'http-status-codes';
import aAsyncHandler from 'express-async-handler';
import asyncHandler from 'express-async-handler';
import { HttpMethod } from '../types/http-method.enum.js';

@injectable()
export abstract class BaseController implements Controller {
Expand All @@ -17,9 +18,24 @@ export abstract class BaseController implements Controller {
return this._router;
}

public addRoutes(routes: Route | Route[]) {
for (const route of [routes].flat(2)) {
this.addRoute(route);
}
}

public addRoute(route: Route) {
const wrapperAsyncHandler = aAsyncHandler(route.handler.bind(this));
this._router[route.method](route.path, wrapperAsyncHandler);
route.method ??= HttpMethod.get;
const wrapperAsyncHandler = asyncHandler(route.handler.bind(this));
const middlewareHandlers = route.middlewares?.map((item) =>
asyncHandler(item.execute.bind(item)),
);
const allHandlers = middlewareHandlers
? [...middlewareHandlers, wrapperAsyncHandler]
: wrapperAsyncHandler;

this._router[route.method](route.path, allHandlers);

this.logger.info(
`Route registered: ${route.method.toUpperCase()} ${route.path}`,
);
Expand Down
7 changes: 5 additions & 2 deletions src/shared/libs/rest/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ export { Controller } from './controller/controller.interface.js';
export { BaseController } from './controller/base-controller.abstract.js';
export { ExceptionFilter } from './exception-filter/exception-filter.interface.js';
export { AppExceptionFilter } from './exception-filter/app-exception-filter.js';
export { RequestParams } from './types/request.params.type.js';
export { RequestBody } from './types/request-body.type.js';
export { RequestBody, RequestParams } from './types/request.type.js';
export { HttpError } from './errors/index.js';
export { Middleware } from './middleware/middleware.interface.js';
export { ValidateObjectIdMiddleware } from './middleware/validate-objectid.middleware.js';
export { ValidateDtoMiddleware } from './middleware/validate-dto.middleware.js';
export { DocumentExistsMiddleware } from './middleware/document-exists.middleware.js';
33 changes: 33 additions & 0 deletions src/shared/libs/rest/middleware/document-exists.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { NextFunction, Request, Response } from 'express';
import { StatusCodes } from 'http-status-codes';

import { Middleware } from './middleware.interface.js';
import { DocumentExists } from '../../../types/index.js';
import { HttpError } from '../errors/index.js';

export class DocumentExistsMiddleware implements Middleware {
constructor(
private readonly service: DocumentExists,
private readonly entityName: string,
private readonly paramName: string,
) {}

public async execute(
{ params }: Request,
_res: Response,
next: NextFunction,
): Promise<void> {
const documentId = params[this.paramName];
const exists = await this.service.exists(documentId);

if (!exists) {
throw new HttpError(
StatusCodes.NOT_FOUND,
`${this.entityName} with ${documentId} not found.`,
'DocumentExistsMiddleware',
);
}

next();
}
}
5 changes: 5 additions & 0 deletions src/shared/libs/rest/middleware/middleware.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { NextFunction, Request, Response } from 'express';

export interface Middleware {
execute(req: Request, res: Response, next: NextFunction): void;
}
26 changes: 26 additions & 0 deletions src/shared/libs/rest/middleware/validate-dto.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { NextFunction, Request, Response } from 'express';
import { ClassConstructor, plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { StatusCodes } from 'http-status-codes';

import { Middleware } from './middleware.interface.js';

export class ValidateDtoMiddleware implements Middleware {
constructor(private dto: ClassConstructor<object>) {}

public async execute(
{ body }: Request,
res: Response,
next: NextFunction,
): Promise<void> {
const dtoInstance = plainToInstance(this.dto, body);
const errors = await validate(dtoInstance);

if (errors.length > 0) {
res.status(StatusCodes.BAD_REQUEST).send(errors);
return;
}

next();
}
}
27 changes: 27 additions & 0 deletions src/shared/libs/rest/middleware/validate-objectid.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { NextFunction, Request, Response } from 'express';
import { Middleware } from './middleware.interface.js';
import { Types } from 'mongoose';
import { HttpError } from '../errors/index.js';
import { StatusCodes } from 'http-status-codes';

export class ValidateObjectIdMiddleware implements Middleware {
constructor(private param: string) {}

public execute(
{ params }: Request,
_res: Response,
next: NextFunction,
): void {
const objectId = params[this.param];

if (Types.ObjectId.isValid(objectId)) {
return next();
}

throw new HttpError(
StatusCodes.BAD_REQUEST,
`${objectId} is invalid ObjectID`,
'ValidateObjectIdMiddleware',
);
}
}
10 changes: 5 additions & 5 deletions src/shared/libs/rest/types/http-method.enum.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export enum HttpMethod {
Get = 'get',
Post = 'post',
Delete = 'delete',
Patch = 'patch',
Put = 'put',
get = 'get',
post = 'post',
delete = 'delete',
patch = 'patch',
put = 'put',
}
1 change: 0 additions & 1 deletion src/shared/libs/rest/types/request-body.type.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export type RequestBody = Record<string, unknown>;
export type RequestParams = Record<string, unknown>;
4 changes: 3 additions & 1 deletion src/shared/libs/rest/types/route.interface.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { NextFunction, Request, Response } from 'express';
import { HttpMethod } from './http-method.enum.js';
import { Middleware } from '../middleware/middleware.interface.js';

export interface Route {
path: string;
method: HttpMethod;
method?: HttpMethod;
handler: (req: Request, res: Response, next: NextFunction) => void;
middlewares?: Middleware[];
}
Loading
Loading