### Run Local Application (Development) Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Starts specific API applications in development mode. Examples include authentication and cats API. ```bash $ yarn start:auth-api:dev $ yarn start:cats-api:dev ``` -------------------------------- ### Install Monorepo Dependencies Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Installs all dependencies required for the monorepo. This is typically the first step after cloning the repository. ```bash yarn monorepo:install ``` -------------------------------- ### Monorepo Development and Operations Commands Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt Provides essential bash commands for setting up, running, testing, building, and managing dependencies within the NestJS monorepo. This includes installing dependencies, starting local infrastructure, running services in development, executing tests, linting, building for production, and managing workspace packages. ```bash # Install all monorepo dependencies yarn monorepo:install # Start infrastructure (MongoDB, Redis, Kibana, Jaeger) yarn infra:local # Access points: # - MongoDB UI: http://0.0.0.0:8082 # - Redis UI: http://0.0.0.0:8081 # - Kibana: http://0.0.0.0:5601/app/home # - Jaeger: http://0.0.0.0:16686/search # Start services in development mode yarn start:auth-api:dev # Auth API on port 4000 yarn start:cats-api:dev # Cats API on port 3000 # Swagger documentation: # - Auth API: http://0.0.0.0:4000/docs # - Cats API: http://0.0.0.0:3000/docs # Run tests yarn test # All unit tests yarn test:e2e # End-to-end tests yarn test:coverage # With coverage report # Lint and format yarn lint # Run ESLint and Prettier # Build for production yarn build auth-api yarn build cats-api # Run in Docker docker-compose up --build # Add new workspace dependencies yarn workspace @app/cats.api add yarn workspace @libs/modules add ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Installs dependencies for a specific project (workspace) within the monorepo. Replace `` with the actual name of the project. ```bash yarn workspace install ``` -------------------------------- ### Run Local Infrastructure Services Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Starts local Docker containers for essential services like MongoDB, Redis, Kibana, and Jaeger. Provides URLs to access these services. ```bash $ yarn infra:local # http://0.0.0.0:8082/ to access mongo # http://0.0.0.0:8081/ to access redis # http://0.0.0.0:5601/app/home to access kibana # http://0.0.0.0:16686/search to access jeager ``` -------------------------------- ### Access External Services with Tracing in TypeScript Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/CONTRIBUTING.md Demonstrates accessing an external HTTP service using an Axios instance configured with tracing. It includes error handling and setting tracing tags for request details. This example assumes the `ApiRequest` type provides tracing capabilities. ```typescript import { IHealthService } from './adapter'; import { Req } from '@nestjs/common'; import { ApiRequest } from 'libs/utils'; async get(@Req() req: ApiRequest): Promise { const URL = 'https://legend-of-github-api.herokuapp.com'; const span = request.tracing.createSpan(URL); let response; try { response = await request.tracing.axios().get(`${URL}/user/full?mikemajesty`); } finally { span.addTags({ headers: response.headers }); span.addTags({ [request.tracing.tags.HTTP_STATUS_CODE]: response.status }); span.finish(); } } ``` ```typescript import { IHealthService } from './adapter'; import { Req } from '@nestjs/common'; import { ApiRequest } from 'libs/utils'; async get(@Req() req: ApiRequest): Promise { req.tracing.setTracingTag(req.tracing.tags.PEER_SERVICE, 'github-scrap-api'); req.tracing.setTracingTag(req.tracing.tags.SPAN_KIND, 'client'); req.tracing.setTracingTag(req.tracing.tags.PEER_HOSTNAME, 'https://github.com/'); await req.tracing.axios().get('https://legend-of-github-api.herokuapp.com/user/full?username=mikemajesty'); return this.healthService.getText(); } ``` -------------------------------- ### Add New Features with CLI Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Installs and uses the `monorepo-nestjs-cli` to generate new features using predefined templates. ```bash npm i -g @mikemajesty/monorepo-nestjs-cli # type and choose your template $ monorepo-nestjs-cli ``` -------------------------------- ### Access Internal Services with Authentication in TypeScript Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/CONTRIBUTING.md Shows how to make a POST request to an internal service, including setting an authorization header and passing a JSON payload. This example assumes the `ApiRequest` type and `secretService` are available and properly configured. ```typescript import { Req } from '@nestjs/common'; import { ApiRequest } from 'libs/utils'; async get(@Req() req: ApiRequest): Promise { await req.tracing .axios({ headers: { Authorization: `Bearer ${req.headers['Authorization']}`, }, }) .post(this.secretService.authAPI.url + '/api/login', { login: 'admin', pass: 'admin' }); return this.healthService.getText(); } ``` -------------------------------- ### JWT Token Service Implementation (TypeScript) Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt This TypeScript service handles JWT token operations including signing, verifying, and decoding. It utilizes an injected `ITokenService` and supports default and custom token expiration times. The example demonstrates authenticating a user and verifying the generated token. ```typescript import { ITokenService } from 'libs/modules/auth/token/adapter'; import { Injectable } from '@nestjs/common'; @Injectable() export class AuthExampleService { constructor(private readonly tokenService: ITokenService) {} async authenticateUser(userId: string) { // Sign a JWT token with 5 minute expiration (default) const { token } = this.tokenService.sign({ userId }); console.log('Generated token:', token); // Verify token is valid try { const decoded = await this.tokenService.verify(token); console.log('Token payload:', decoded); // { userId: '...', iat: ..., exp: ... } } catch (error) { console.error('Token verification failed:', error.message); throw new UnauthorizedException('Invalid token'); } // Decode token without verification (useful for debugging) const payload = this.tokenService.decode(token); console.log('Decoded payload:', payload); return token; } // Sign with custom expiration generateLongLivedToken(userId: string) { return this.tokenService.sign( { userId, role: 'admin' }, { expiresIn: '24h' } ); } } ``` -------------------------------- ### Create Access User in MongoDB Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Provides instructions to create a new user document in the MongoDB database and demonstrates how to obtain an access token using cURL. ```bash http://0.0.0.0:8082/db/monorepo_auth/users # Click [New Document] { "_id": ObjectID(), "login": "", "pass": "" } curl -X 'POST' 'http://0.0.0.0:4000/api/login' -H 'accept: application/json' -H 'Content-Type: application/json' -d '{ "login": "", "pass": "" }' ``` -------------------------------- ### Run Application (Production Environment) Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Builds and runs the application using Docker Compose for development, staging, or production environments. ```bash $ docker-compose up --build ``` -------------------------------- ### List Workspaces Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Displays a list of all available workspaces (projects and libraries) within the monorepo. ```bash $ yarn workspaces info ``` -------------------------------- ### Run Project Linting Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Applies linting rules to a specific project (workspace) within the monorepo. Replace `` with the target project. ```bash $ yarn workspace lint ``` -------------------------------- ### Run Monorepo Linting Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Applies linting rules across all projects in the monorepo to ensure code quality and consistency. ```bash $ yarn lint ``` -------------------------------- ### Run Monorepo Unit Tests Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Executes all unit tests across the entire monorepo. ```bash $ yarn test ``` -------------------------------- ### Run E2E Tests Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Executes the end-to-end tests for the monorepo. ```bash $ yarn test:e2e ``` -------------------------------- ### Run Specific Project Unit Tests Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Executes unit tests for a particular project within the monorepo. Replace `main.api`, `auth.api`, or `libs` with the target project name. ```bash $ yarn test main.api $ yarn test auth.api $ yarn test libs ``` -------------------------------- ### Add Library to Project Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Adds a specific library to a project within the monorepo. Replace `` with the target project and `` with the library to add. ```bash yarn workspace add ``` -------------------------------- ### Structured Logger Service with Pino.js (TypeScript) Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt Implements a structured logging service using Pino.js, supporting console output with pretty formatting and Elasticsearch integration. It allows for different log levels and context-aware logging. The service is injected via an interface `ILoggerService`. ```typescript import { ILoggerService } from 'libs/modules/global/logger/adapter'; import { Injectable } from '@nestjs/common'; @Injectable() export class OrderService { constructor(private readonly logger: ILoggerService) { this.logger.setApplication('order-service'); } async processOrder(orderId: string) { // Simple log message (green in console) this.logger.log('Starting order processing...'); // Trace level with context this.logger.trace({ message: 'Fetching order details', context: 'OrderService/processOrder', obj: { orderId } }); // Info level with structured data this.logger.info({ message: 'Order validated successfully', context: 'OrderService', obj: { orderId, status: 'validated', timestamp: Date.now() } }); // Warning level this.logger.warn({ message: 'Low inventory detected', context: 'OrderService', obj: { orderId, remainingStock: 5 } }); try { // Business logic here throw new Error('Payment gateway timeout'); } catch (error) { // Error logging with stack trace this.logger.error( error, 'Order processing failed', 'OrderService/processOrder' ); // Fatal error (critical) // this.logger.fatal(error, 'Critical system failure', 'OrderService'); } } } // All logs are automatically sent to: // - Console with pretty formatting and colors // - Elasticsearch index: monorepo-logs-YYYY-MM // - Include traceid, timestamp, application name, and context ``` -------------------------------- ### Implement Redis Cache Operations with TTL in TypeScript Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt Demonstrates how to use a Redis cache service for storing and retrieving data with time-to-live (TTL) management. Supports simple key-value pairs and hash operations. Requires an implementation of ICacheService. ```typescript import { ICacheService } from 'libs/modules/cache/adapter'; import { Injectable } from '@nestjs/common'; @Injectable() export class ProductCacheService { constructor(private readonly cache: ICacheService) {} async cacheProductData() { // Set simple key-value with 60 second expiration await this.cache.set('product:123', JSON.stringify({ id: '123', name: 'Laptop', price: 1299.99 })); await this.cache.pExpire('product:123', 60000); // milliseconds // Get cached value const cached = await this.cache.get('product:123'); const product = JSON.parse(cached as string); console.log('Cached product:', product); // Hash operations for complex objects await this.cache.hSet('user:456', 'name', 'John Doe'); await this.cache.hSet('user:456', 'email', 'john@example.com'); await this.cache.hSet('user:456', 'age', '30'); // Get single hash field const email = await this.cache.hGet('user:456', 'email'); console.log('Email:', email); // 'john@example.com' // Get all hash fields const user = await this.cache.hGetAll('user:456'); console.log('User:', user); // { name: 'John Doe', email: '...', age: '30' } // Set multiple keys in transaction await this.cache.setMulti([ { key: 'cart:1', value: 'item1' }, { key: 'cart:1', value: 'item2' }, { key: 'cart:1', value: 'item3' } ]); // Delete key await this.cache.del('product:123'); // Check connection health await this.cache.isConnected(); // throws if disconnected } } ``` -------------------------------- ### Generate Test Coverage Report Source: https://github.com/mikemajesty/nestjs-monorepo/blob/main/README.md Generates a coverage report for all executed tests within the monorepo. ```bash $ yarn test:coverage ``` -------------------------------- ### Create Cat Record with JWT Protection Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt This endpoint allows for the creation of cat records within the cats API. It requires a valid JWT token for authorization, provided in the 'Authorization' header as a Bearer token. The response includes the created cat's ID and a success flag, or an unauthorized error if the token is missing or invalid. ```bash # Get token from auth-api first (see Login Endpoint above) TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." # Create a cat record curl -X 'POST' \ 'http://0.0.0.0:3000/api/cats' \ -H 'accept: application/json' \ -H 'Authorization: Bearer '"$TOKEN"' \ -H 'Content-Type: application/json' \ -d '{ "name": "Fluffy", "age": 3, "breed": "Persian", "status": "approved" }' # Response (201 Created): { "id": "507f1f77bcf86cd799439011", "created": true } # Unauthorized Response (401): { "error": { "code": 401, "traceid": "uuid-v4-string", "message": "no token provided", "timestamp": "10/12/2025 14:30:45", "path": "api/cats" } } ``` -------------------------------- ### Custom API Exception Handling in TypeScript Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt Demonstrates how to use a custom ApiException class for standardized error responses in a NestJS application. It handles different error scenarios, including validation, precondition failures, and external API errors, while integrating with global exception filters for logging and tracing. ```typescript import { ApiException } from 'libs/utils/exception'; import { HttpStatus, Injectable } from '@nestjs/common'; @Injectable() export class PaymentService { async processPayment(amount: number) { if (amount <= 0) { // Simple error message throw new ApiException( 'Amount must be greater than zero', HttpStatus.BAD_REQUEST ); } if (amount > 10000) { // Error with context for debugging throw new ApiException( 'Payment amount exceeds maximum allowed', HttpStatus.PRECONDITION_FAILED, 'PaymentService/processPayment' ); } try { // External API call const result = await this.externalPaymentGateway(amount); } catch (error) { // Wrap external errors throw new ApiException( 'Payment gateway unavailable', HttpStatus.SERVICE_UNAVAILABLE, 'PaymentService' ); } } } // ApiException automatically provides: // - statusCode: HTTP status code // - context: Service/method that threw the error // - traceid: Unique identifier for request tracing // - timestamp: Error occurrence time // - Proper logging through global exception filter ``` -------------------------------- ### Authentication API - Login Endpoint Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt Authenticates a user by validating credentials and issuing JWT access tokens. Requires a user to exist in the MongoDB database. ```APIDOC ## POST /api/login ### Description User authentication endpoint that validates credentials and issues JWT access tokens. ### Method POST ### Endpoint `/api/login` ### Parameters #### Request Body - **login** (string) - Required - The username for authentication. - **pass** (string) - Required - The password for authentication. ### Request Example ```json { "login": "testuser", "pass": "testpass123" } ``` ### Response #### Success Response (200 OK) - **token** (string) - The JWT access token. #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` #### Error Response (412 Precondition Failed) - **error** (object) - Contains error details. - **code** (number) - HTTP status code (412). - **traceid** (string) - Unique identifier for the request trace. - **message** (string) - Error message indicating invalid credentials. - **timestamp** (string) - Timestamp of the error. - **path** (string) - The endpoint path that caused the error. #### Response Example ```json { "error": { "code": 412, "traceid": "uuid-v4-string", "message": "username or password is invalid.", "timestamp": "10/12/2025 14:30:45", "path": "api/login" } } ``` ``` -------------------------------- ### Authenticate User with JWT Token Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt This endpoint validates user credentials and issues a JWT access token upon successful authentication. It handles both successful login responses and precondition failed errors for invalid credentials. Requires a user to be pre-created in MongoDB. ```bash # Create a user in MongoDB first # Access mongo-express at http://0.0.0.0:8082/db/monorepo_auth/users # Add document: { "_id": ObjectID(), "login": "testuser", "pass": "testpass123" } # Login to get JWT token curl -X 'POST' \ 'http://0.0.0.0:4000/api/login' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -d '{ "login": "testuser", "pass": "testpass123" }' # Response (200 OK): { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } # Error Response (412 Precondition Failed): { "error": { "code": 412, "traceid": "uuid-v4-string", "message": "username or password is invalid.", "timestamp": "10/12/2025 14:30:45", "path": "api/login" } } ``` -------------------------------- ### Cats API - Create Cat Endpoint Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt Allows creating new cat records. This endpoint is protected and requires a valid JWT for authorization. ```APIDOC ## POST /api/cats ### Description Protected endpoint for creating cat records with JWT authentication. ### Method POST ### Endpoint `/api/cats` ### Parameters #### Query Parameters - **Authorization** (string) - Required - JWT token in the format `Bearer `. #### Request Body - **name** (string) - Required - The name of the cat. - **age** (number) - Required - The age of the cat. - **breed** (string) - Optional - The breed of the cat. - **status** (string) - Optional - The status of the cat (e.g., 'approved'). ### Request Example ```bash TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." curl -X 'POST' \ 'http://0.0.0.0:3000/api/cats' \ -H 'accept: application/json' \ -H 'Authorization: Bearer "$TOKEN"' \ -H 'Content-Type: application/json' \ -d '{ "name": "Fluffy", "age": 3, "breed": "Persian", "status": "approved" }' ``` ### Response #### Success Response (201 Created) - **id** (string) - The unique identifier of the created cat record. - **created** (boolean) - Indicates if the cat record was successfully created. #### Response Example ```json { "id": "507f1f77bcf86cd799439011", "created": true } ``` #### Unauthorized Response (401) - **error** (object) - Contains error details. - **code** (number) - HTTP status code (401). - **traceid** (string) - Unique identifier for the request trace. - **message** (string) - Error message indicating missing or invalid token. - **timestamp** (string) - Timestamp of the error. - **path** (string) - The endpoint path that caused the error. #### Response Example ```json { "error": { "code": 401, "traceid": "uuid-v4-string", "message": "no token provided", "timestamp": "10/12/2025 14:30:45", "path": "api/cats" } } ``` ``` -------------------------------- ### Health Check Endpoint Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt Monitors the availability and readiness of the services. Returns a status indicating if the service is operational. ```APIDOC ## GET /health ### Description Endpoint for monitoring service availability and readiness. ### Method GET ### Endpoint `/health` ### Parameters None ### Request Example ```bash # Check auth-api health curl -X 'GET' 'http://0.0.0.0:4000/health' # Check cats-api health curl -X 'GET' 'http://0.0.0.0:3000/health' ``` ### Response #### Success Response (200 OK) - **status** (string) - Indicates the health status of the service (e.g., 'ok'). - **timestamp** (string) - The timestamp when the health check was performed. #### Response Example ```json { "status": "ok", "timestamp": "2025-12-10T14:30:45.123Z" } ``` ``` -------------------------------- ### JWT Token Service Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt A service for signing, verifying, and decoding JWT tokens, with support for automatic expiration. ```APIDOC ## JWT Token Service Utility ### Description Provides methods to manage JSON Web Tokens (JWT), including signing new tokens, verifying existing ones, and decoding their payload. Supports custom expiration times. ### Methods - **sign(payload: object, options?: object): { token: string }**: Creates and signs a new JWT. `options` can include `expiresIn` (e.g., '5m', '24h'). - **verify(token: string): Promise**: Verifies the signature and expiration of a JWT. Throws an error if verification fails. - **decode(token: string): object**: Decodes the JWT payload without verifying the signature. Useful for inspecting token contents. ### Usage Example (TypeScript) ```typescript import { ITokenService } from 'libs/modules/auth/token/adapter'; import { Injectable } from '@nestjs/common'; @Injectable() export class AuthExampleService { constructor(private readonly tokenService: ITokenService) {} async authenticateUser(userId: string) { // Sign a JWT token with default 5 minute expiration const { token } = this.tokenService.sign({ userId }); console.log('Generated token:', token); // Verify token is valid try { const decoded = await this.tokenService.verify(token); console.log('Token payload:', decoded); // { userId: '...', iat: ..., exp: ... } } catch (error) { console.error('Token verification failed:', error.message); throw new UnauthorizedException('Invalid token'); } // Decode token without verification (for inspection) const payload = this.tokenService.decode(token); console.log('Decoded payload:', payload); return token; } // Sign with custom expiration generateLongLivedToken(userId: string) { return this.tokenService.sign( { userId, role: 'admin' }, { expiresIn: '24h' } // Token valid for 24 hours ); } } ``` ``` -------------------------------- ### Apply JWT Authentication Middleware to NestJS Routes in TypeScript Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt Configures authentication middleware for NestJS routes, automatically verifying JWT tokens from the Authorization header, extracting user information, and adding it to request headers. Also handles trace ID injection. ```typescript import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common'; import { IsLoggedMiddleware } from 'libs/utils/middleware/auth/is-logged.middleware'; import { ProductController } from './product.controller'; @Module({ controllers: [ProductController], }) export class ProductModule implements NestModule { configure(consumer: MiddlewareConsumer) { // Apply authentication to specific routes consumer .apply(IsLoggedMiddleware) .forRoutes(ProductController); } } // Middleware automatically: // 1. Extracts token from Authorization: Bearer header // 2. Verifies token signature and expiration // 3. Adds user ID to request.headers.user // 4. Adds traceid to request.headers.traceid for logging // 5. Throws UnauthorizedException if token is missing/invalid // In your controller: import { Controller, Post, Headers } from '@nestjs/common'; @Controller('products') export class ProductController { @Post() async create(@Headers('user') userId: string) { console.log('Authenticated user:', userId); // userId is automatically extracted from JWT token } } ``` -------------------------------- ### Generic Repository for MongoDB CRUD Operations (TypeScript) Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt Provides type-safe CRUD operations for MongoDB collections using Mongoose. It abstracts common database interactions, reducing boilerplate code. Dependencies include Mongoose and NestJS modules. ```typescript import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Repository } from 'libs/modules'; import { Model } from 'mongoose'; // Define your schema and document type interface Product { name: string; price: number; category: string; } // Assuming ProductDocument is defined elsewhere and extends Mongoose Document interface ProductDocument extends Document { name: string; price: number; category: string; } @Injectable() export class ProductRepository extends Repository { constructor( @InjectModel('Product') private readonly model: Model ) { super(model); } async createProduct(data: Product) { // Create a new document const result = await this.create(data); console.log('Created:', result); // { id: '507f...', created: true } return result; } async findProducts() { // Find all products const all = await this.findAll(); // Find with filter const filtered = await this.find({ category: 'electronics' }); // Find one with options const product = await this.findOne( { name: 'iPhone' }, { sort: { price: -1 } } ); // Find by ID const byId = await this.findById('507f1f77bcf86cd799439011'); return { all, filtered, product, byId }; } async updateProduct(id: string) { // Update one document const result = await this.updateOne( { _id: id }, { $set: { price: 999.99 } } ); console.log('Modified:', result.modifiedCount); // Update many documents const bulk = await this.updateMany( { category: 'electronics' }, { $inc: { price: 50 } } ); console.log('Updated:', bulk.modifiedCount); } async deleteProduct(id: string) { const result = await this.remove({ _id: id }); console.log('Deleted:', result); // { deletedCount: 1, deleted: true } } } ``` -------------------------------- ### Access Environment Variables with Type Safety in TypeScript Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt Utilizes a secrets service to provide type-safe access to application configuration, including database credentials, API settings, and infrastructure URLs. Requires an implementation of ISecretsService. ```typescript import { ISecretsService } from 'libs/modules/global/secrets/adapter'; import { Injectable } from '@nestjs/common'; @Injectable() export class DatabaseSetupService { constructor(private readonly secrets: ISecretsService) {} getConfiguration() { // Database configuration const dbConfig = this.secrets.database; console.log('MongoDB:', { host: dbConfig.host, // 0.0.0.0 port: dbConfig.port, // 27017 user: dbConfig.user, // admin pass: dbConfig.pass // admin }); // API configurations const authPort = this.secrets.authAPI.port; // 4000 const authUrl = this.secrets.authAPI.url; // http://0.0.0.0:4000 const jwtSecret = this.secrets.authAPI.jwtToken; // ca6d0e6f-... const mainPort = this.secrets.mainAPI.port; // 3000 const mainUrl = this.secrets.mainAPI.url; // http://0.0.0.0:3000 // Infrastructure URLs const elkUrl = this.secrets.ELK_URL; // http://0.0.0.0:9200/ const redisUrl = this.secrets.REDIS_URL; // redis://0.0.0.0:6379 const mongoExpress = this.secrets.MONGO_EXPRESS_URL; // http://0.0.0.0:8082 const redisCommander = this.secrets.REDIS_COMMANDER_URL; // http://0.0.0.0:8081 const kibanaUrl = this.secrets.KIBANA_URL; // http://0.0.0.0:5601/app/home const jeagerUrl = this.secrets.JEAGER_URL; // http://0.0.0.0:16686/search // Environment settings const env = this.secrets.ENV; // dev | hml | prd const logLevel = this.secrets.LOG_LEVEL; // trace | info | warn | error return { dbConfig, authPort, mainPort, env }; } } ``` -------------------------------- ### Service Health Check Endpoint Source: https://context7.com/mikemajesty/nestjs-monorepo/llms.txt This endpoint provides a health status check for the NestJS microservices. It can be used to monitor the availability and readiness of services like the authentication API or the cats API. A successful response indicates the service is operational. ```bash # Check auth-api health curl -X 'GET' 'http://0.0.0.0:4000/health' # Check cats-api health curl -X 'GET' 'http://0.0.0.0:3000/health' # Response (200 OK): { "status": "ok", "timestamp": "2025-12-10T14:30:45.123Z" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.