npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@develop-x/nest-response

v1.0.11

Published

## Overview

Readme

@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.