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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@zabih-dev/nest-api-response

v1.2.2

Published

API Response Wrapper Library for NestJS

Downloads

343

Readme

API Response Wrapper Library for NestJS

This NestJS library provides a standardized API response wrapper that ensures consistent response structures across your application. It includes an interceptor to automatically wrap responses in a DTO format, and also allows flexibility by skipping this behavior using a decorator.

Features

  • Automatic Response Wrapping: Standardizes the API response format with success, status code, message, and error handling.
  • Customizable Responses: Allows returning raw responses by using the @RawResponse() decorator to skipping the wrapped response.
  • Validation Error Handling: Includes a class validator to return errors based on the validation.

Installation

Install the package using npm:

npm install @zabih-dev/nest-api-response

Usage

Open the app.module.ts file and add ApiResponseModule to the imports array.

import { ApiResponseModule } from '@zabih-dev/nest-api-response';
@Module({
  imports: [ApiResponseModule], // Add this line
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Now all routes will return a wrapped response

By default, all API responses will automatically be wrapped in the following format:

export class ApiResponseDto<TData> {
  success: boolean;
  statusCode: number;
  message?: string;
  errors?: ValidationErrorDto[];
  data: TData | TData[];
}

And the ValidationErrorDto is used for handling class validation errors.

export class ValidationErrorDto {
  filed: string;
  messages: string[];
}

Example of Wrapped Response

For a successful response:

@Controller()
export class AppController {
  // will be wrapped by the api response
  @Get('users')
  getUsers() {
    return [
      { id: 1, name: 'John' },
      { id: 2, name: 'Petter' },
    ];
  }
}

Wrapped Response:

{
  "success": true,
  "statusCode": 200,
  "message": null,
  "data": [
    {
      "id": 1,
      "name": "John"
    },
    {
      "id": 2,
      "name": "Petter"
    }
  ]
}

Skipping the Response Wrapper

To return a raw response without wrapping it in ApiResponseDto, simply use the @RawResponse() decorator on the handler:

import { RawResponse } from '@zabih-dev/nest-api-response';

@Controller()
export class AppController {
  @RawResponse() // add it to skip the response wrapper
  @Get('users')
  getUsers() {
    return [
      { id: 1, name: 'John' },
      { id: 2, name: 'Petter' },
    ];
  }
}

Response without the wrapping:

[
  {
    "id": 1,
    "name": "John"
  },
  {
    "id": 2,
    "name": "Petter"
  }
]

For a validation error response:

Consider we have a /signin route

// controller.ts
signin(@Body() dto: AuthDto) {
  return dto;
}

// dto.ts file
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
export class AuthDto {
  @IsEmail()
  @IsNotEmpty()
  email: string;

  @IsString()
  @IsNotEmpty()
  password: string;
}

In the case of a validation failure, the response will be like this:

{
  "success": false,
  "statusCode": 400,
  "message": "Validation failed",
  "errors": [
    {
      "filed": "email",
      "messages": ["email should not be empty", "email must be an email"]
    },
    {
      "filed": "password",
      "messages": ["password should not be empty", "password must be a string"]
    }
  ],
  "data": null
}

Contributing

Feel free to contribute by submitting a pull request or opening an issue if you find any bugs.

License

MIT License