Class 06: Middleware, Interceptor, Guard
Middleware là gì? Ứng dụng trong logging và xác thực
Middleware là gì?
Ví dụ: Tạo middleware ghi log request
// common/middleware/logger.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
}
}Áp dụng middleware
Interceptor: response transformation, timeout, logging
Interceptor là gì?
Ví dụ: Interceptor thêm metadata
Áp dụng interceptor toàn cục
Guard: phân quyền, bảo vệ route
Guard là gì?
Ví dụ: Guard đơn giản kiểm tra header x-api-key
x-api-keyÁp dụng guard cho controller hoặc method
Thực hành: Tạo Middleware kiểm tra request, Guard chặn IP
Mục tiêu
Bước 1: Middleware kiểm tra header
Bước 2: Guard chặn IP
Bước 3: Sử dụng guard
Bài tập thực hành
Mục tiêu
Yêu cầu
Gợi ý test với Postman
Kết luận
PreviousClass 05: Quan hệ trong Database (OneToMany, ManyToOne) với TypeORMNextClass 07: Authentication – JWT
Last updated