NestJS 攔截器實戰:用兩個小檔案統一 API 回應格式並記錄請求耗時
Every response from my API looks the same, and it's two small files: NestJS interceptors in a real project
FaceMark 以 NestJS 的兩個攔截器統一所有成功 API 回應的格式,並記錄每個請求的方法、URL、狀態碼、IP 和耗時。錯誤由獨立的 exception filter 處理,因此不共用成功回應的格式;記錄亦展示了 40ms 快取命中與數秒 AI 呼叫的耗時差異。
I'm a junior full-stack developer from Alexandria, Egypt. This is another post about FaceMark, my face-recognition attendance system (a NestJS API plus a Python AI service), and it's about the two smallest files in the repo that touch every request: the interceptors.
The problem they solve
An API with twenty endpoints drifts. One controller returns the entity, another returns { message: "ok" }, a third returns whatever the service felt like. The frontend ends up with a different parsing rule per screen, and nobody knows how slow anything is until a user complains.
NestJS's answer is interceptors: code that wraps every handler, sees the request going in and the response going out, and can transform either. FaceMark uses two.
One response shape for everything
// src/common/interceptors/transform.interceptor.ts
export interface Response<T> {
success: boolean;
data: T;
timestamp: string;
}
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
return next.handle().pipe(
map((data) => ({
success: true,
data: data || null,
timestamp: new Date().toISOString(),
})),
);
}
}
Thirty lines, and every successful response from every endpoint now looks like { success: true, data: ..., timestamp: ... }. The frontend writes its parsing logic once. next.handle() is the actual controller doing its work; the interceptor just maps over what comes back.
The honest limitation I learned while writing this: it only wraps successful responses. Errors go through the exception filter instead, which is a separate piece with its own shape. So "every response looks the same" really means "every response has a defined shape", and there are two of them.
Free request timing
// src/common/interceptors/logging.interceptor.ts
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
private readonly logger = new Logger('HTTP');
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const request = context.switchToHttp().getRequest();
const { method, url, ip } = request;
const now = Date.now();
return next.handle().pipe(
tap((data) => {
const response = context.switchToHttp().getResponse();
this.logger.log(
`${method} ${url} ${response.statusCode} - ${ip} - ${Date.now() - now}ms`,
);
}),
);
}
}
Every request gets one log line: method, URL, status, IP, and milliseconds. No APM tool, no dashboard, no config. When I was tuning the face-recognition call, the one that goes out to the Python service, these lines were how I saw the difference between a 40ms cache hit and a multi-second AI call without touching the endpoints themselves.
That's the real pitch for interceptors as a junior: cross-cutting concerns (logging, shaping, timing) live in one place, and your controllers stay about the business.
What I'd tell another junior dev
If you copy-paste response formatting into a second controller, stop and write an interceptor. The second copy is when it becomes a convention; the third is when it becomes a bug farm.
tap vs map matters. tap observes (logging), map changes (transform). Mixing them up is the classic first interceptor bug: logging inside a map that forgets to return the data.
Interceptors run outside-in, then inside-out. If you stack two, the first one registered sees the request first and the response last. Worth knowing before you wonder why your log line includes or excludes the transform step.
Everything above is from the real repo.
I'm a junior full-stack developer (Angular, NestJS, TypeScript, Python) in Alexandria, Egypt, open to junior roles and freelance work. More posts from this project:
- Circuit breaker + WAL engine: https://dev.to/ziadtaha/i-wrote-a-circuit-breaker-and-a-bitcask-style-wal-engine-for-my-face-recognition-api-with-real-1gcp
The NestJS-to-Python boundary: https://dev.to/ziadtaha/my-nestjs-api-talks-to-a-python-ai-microservice-heres-how-i-keep-the-boundary-honest-with-real-160g
GitHub: https://github.com/ZiadtahaM
Email: ziad.taha3456@gmail.com
dev.to: https://dev.to/ziadtaha
來源:DEV Community · dev.to