1.0.11 • Published 12 months ago

@develop-x/nest-response v1.0.11

Weekly downloads
-
License
-
Repository
-
Last release
12 months ago

@develop-x/nest-response

Overview

@develop-x/nest-response is a NestJS package that provides standardized response formatting for your APIs. It ensures consistent response structure across your application and includes OpenTelemetry trace ID integration for better observability.

Installation

npm install @develop-x/nest-response

Features

  • Standardized Response Format: Consistent API response structure
  • Success and Error Responses: Built-in methods for both success and error responses
  • OpenTelemetry Integration: Automatic trace ID inclusion in response metadata
  • Timestamp Metadata: Automatic timestamp generation for all responses
  • TypeScript Support: Full TypeScript support with generic types

Usage

Module Import

Import the ResponseModule in your application module:

import { Module } from '@nestjs/common';
import { ResponseModule } from '@develop-x/nest-response';

@Module({
  imports: [ResponseModule],
  // ... other module configuration
})
export class AppModule {}

Basic Usage

Inject the ResponseHelper service in your controllers:

import { Controller, Get } from '@nestjs/common';
import { ResponseHelper } from '@develop-x/nest-response';

@Controller('users')
export class UsersController {
  constructor(private readonly responseHelper: ResponseHelper) {}

  @Get()
  async getUsers() {
    const users = [
      { id: 1, name: 'John Doe' },
      { id: 2, name: 'Jane Smith' }
    ];

    return this.responseHelper.success(users, 'Users retrieved successfully');
  }

  @Get('error-example')
  async getError() {
    return this.responseHelper.error('Something went wrong', 500);
  }
}

API Reference

ResponseHelper Methods

success(data: T, message: string, code?: number)

Creates a successful response with the provided data.

Parameters:

  • data: T - The response data (generic type)
  • message: string - Success message
  • code: number - HTTP status code (default: 200)

Returns: ResponsePayload<T>

Example:

const response = this.responseHelper.success(
  { id: 1, name: 'John' },
  'User created successfully',
  201
);

error(message: string, code?: number)

Creates an error response.

Parameters:

  • message: string - Error message
  • code: number - HTTP status code (default: 500)

Returns: ResponsePayload<null>

Example:

const response = this.responseHelper.error('User not found', 404);

Response Structure

All responses follow this standardized structure:

interface ResponsePayload<T = any> {
  code: number;        // HTTP status code
  message: string;     // Response message
  data: T;            // Response data (null for errors)
  meta: Meta;         // Response metadata
}

interface Meta {
  traceId?: string;   // OpenTelemetry trace ID
  timestamp: string;  // ISO timestamp
}

Response Examples

Success Response

{
  "code": 200,
  "message": "Users retrieved successfully",
  "data": [
    { "id": 1, "name": "John Doe" },
    { "id": 2, "name": "Jane Smith" }
  ],
  "meta": {
    "traceId": "1234567890abcdef",
    "timestamp": "2023-12-01T10:30:00.000Z"
  }
}

Error Response

{
  "code": 404,
  "message": "User not found",
  "data": null,
  "meta": {
    "traceId": "1234567890abcdef",
    "timestamp": "2023-12-01T10:30:00.000Z"
  }
}

Advanced Usage

Custom Response Wrapper

You can create a custom decorator to automatically wrap your controller responses:

import { applyDecorators, UseInterceptors } from '@nestjs/common';
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ResponseHelper } from '@develop-x/nest-response';

@Injectable()
export class ResponseInterceptor implements NestInterceptor {
  constructor(private readonly responseHelper: ResponseHelper) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map(data => {
        if (data && typeof data === 'object' && 'code' in data) {
          // Already formatted response
          return data;
        }
        return this.responseHelper.success(data, 'Success');
      })
    );
  }
}

// Usage in controller
@UseInterceptors(ResponseInterceptor)
@Controller('api')
export class ApiController {
  @Get('data')
  getData() {
    return { message: 'Hello World' }; // Will be automatically wrapped
  }
}

Integration with Exception Filters

The response helper works well with NestJS exception filters:

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Response } from 'express';
import { ResponseHelper } from '@develop-x/nest-response';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private readonly responseHelper: ResponseHelper) {}

  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();

    const errorResponse = this.responseHelper.error(
      exception.message,
      status
    );

    response.status(status).json(errorResponse);
  }
}

OpenTelemetry Integration

The package automatically includes OpenTelemetry trace IDs in the response metadata when available. This helps with:

  • Request Tracing: Link responses to distributed traces
  • Debugging: Easier troubleshooting with trace correlation
  • Monitoring: Better observability across your microservices

Best Practices

  1. Consistent Usage: Use the ResponseHelper for all API responses
  2. Meaningful Messages: Provide clear, user-friendly messages
  3. Proper Status Codes: Use appropriate HTTP status codes
  4. Error Handling: Combine with exception filters for comprehensive error handling
  5. Type Safety: Leverage TypeScript generics for type-safe responses

Dependencies

  • @nestjs/common: NestJS common utilities
  • @opentelemetry/api: OpenTelemetry API for trace integration

License

ISC

Support

For issues and questions, please refer to the project repository or contact the development team.

1.0.11

12 months ago

1.0.9

12 months ago

1.0.8

12 months ago

1.0.7

12 months ago

1.0.6

12 months ago

1.0.5

12 months ago

1.0.4

12 months ago

1.0.3

12 months ago

1.0.2

12 months ago

1.0.1

12 months ago

1.0.0

1 year ago