feat: initialize NestJS application with global error handling and response standardization

- Added nest-cli.json for NestJS configuration.
- Created package.json with dependencies and scripts for building, testing, and linting.
- Implemented AppController and AppService with a basic "Hello World!" response.
- Introduced ContextModule and ContextService for managing request-scoped context.
- Developed custom decorators for response messages and standardized error handling.
- Created global exception filter to handle various error types and format responses.
- Implemented response standardization interceptor to wrap successful responses.
- Added middleware for generating unique request IDs.
- Established DTOs for API responses and error handling.
- Configured TypeScript settings for the project.
- Set up Jest for testing with end-to-end test cases.
This commit is contained in:
2025-11-18 06:11:40 +06:00
commit e04b14265b
30 changed files with 3076 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
/**
* src/common/middleware/request-id.middleware.ts
* * This middleware generates a unique request ID (using crypto)
* * and sets it in the AsyncLocalStorage context for every request.
*/
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { requestContext, RequestContextStore } from '../context/storage';
import { REQUEST_ID_KEY } from '../context/context.service';
import { randomUUID } from 'crypto'; // Built-in Node.js module
@Injectable()
export class RequestIdMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
// Attempt to get ID from header (for tracing across services)
// Otherwise, generate a new unique ID
const requestId = (req.headers['x-request-id'] as string) || randomUUID();
// Create a new Map to store context data for this request
const store: RequestContextStore = new Map();
store.set(REQUEST_ID_KEY, requestId);
// Also add the request ID to the response header
res.setHeader('x-request-id', requestId);
// Run the rest of the request chain *within* the async context
requestContext.run(store, () => {
next();
});
}
}