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

@hodfords/nestjs-response

v10.2.4

Published

Standardizes and validates API responses in NestJS for consistent and reliable communication

Downloads

313

Readme

Installation 🤖

To begin using it, we first install the required dependencies.

npm install @hodfords/nestjs-response

Interceptor Setup 🚀

  • Global Interceptor (Recommended):

Global interceptors are applied across the entire application. To set up a global interceptor, you can register it in the providers array in your module.

import { APP_INTERCEPTOR } from '@nestjs/core';
import { ResponseInterceptor } from '@hodfords/nestjs-response';

@Module({
    providers: [
        {
            provide: APP_INTERCEPTOR,
            useClass: ResponseInterceptor
        }
    ]
})
export class AppModule {}
  • Interceptor with Decorator:

For microservices or specific scenarios, use the @UseInterceptors decorator to apply interceptors at the controller or method level. However, it's generally recommended to use global interceptors.

import { Controller } from '@nestjs/common';
import { UseResponseInterceptor } from '@hodfords/nestjs-response';

@Controller()
@UseResponseInterceptor()
export class AppController {}

Usage 🚀

@ResponseModel()

Use the @ResponseModel decorator when an API return single response type.

Parameter:

  • responseClass: The class that defines the response model.
  • isArray (optional): Set to true if the response is an array of responseClass. Defaults to false.
  • isAllowEmpty (optional): Set to true if the response can be empty. Defaults to false.

Example of usage:

import { ResponseModel } from '@hodfords/nestjs-response';
import { Get } from '@nestjs/common';
import { IsNotEmpty, IsString } from 'class-validator';

class UserResponse {
    @IsNotEmpty()
    @IsString()
    name: string;
}

export class UserController {
    @Get()
    @ResponseModel(UserResponse, true)
    getAllUser() {
        return [{ name: 'John' }];
    }
}

@ResponseModels()

Use the @ResponseModels decorator when an API might return multiple response types.

Parameter:

  • ...responseClasses: A list of response classes or arrays of response classes.

Example of usage:

import { ResponseModels } from '@hodfords/nestjs-response';
import { Controller, Get, Param } from '@nestjs/common';
import { UserResponse } from './responses/user.response';
import { UserPaginationResponse } from './responses/user-pagination.response';

@Controller()
export class AppController {
    @Get('list-models/:type')
    @ResponseModels(Number, [Number], UserPaginationResponse, [UserResponse], undefined, null)
    getModels(@Param('type') type: string) {
        if (type == 'undefined') {
            return undefined;
        }
        if (type == 'pagination') {
            return {
                items: [{ name: 'John' }, { name: 'Daniel' }],
                total: 2,
                lastPage: 1,
                perPage: 10,
                currentPage: 1
            };
        }
        if (type == 'multiple') {
            return [{ name: 'John' }, { name: 'Daniel' }];
        }
        if (type == 'list-number') {
            return [123, 456];
        }
        if (type == 'number') {
            return 456;
        }
        return null;
    }
}

Exception Handling

When the response data does not match the expected model, a validation exception will be raised. This ensures that the API returns data conforming to the defined structure.

Example Case: If a property is expected to be a string, but a number is returned, a validation error will occur.

import { ResponseModel } from '@hodfords/nestjs-response';
import { Get } from '@nestjs/common';
import { IsString } from 'class-validator';

class UserResponse {
    @IsString()
    name: string;
}

export class UserController {
    @Get()
    @ResponseModel(UserResponse)
    getUser() {
        return { name: 123 }; // Error: name must be a number ...
    }
}

License

This project is licensed under the MIT License