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

nestjs-response-schema

v0.0.6

Published

A package for setting up strict NestJS response schema's

Downloads

13

Readme

nestjs-response-schema

A package for declaring and enforcing responses in NestJS

Declaring responses and response DTO's has always been difficult in NestJS, atleast that is what I think.

NestJS has had class-transformer support for a while, allowing you to declaratively expose/exclude properties from entities when recieving them in a request or using them in a response. Within class-transformer however it is more difficult to make specific response dto's that expose certain properties and when done, it is difficult to make nested structures.

To get both these things right, a lot of nested class structures are needed which requires a lot of work to setup. To make this easier, nestjs-response-schema comes with a object structure to easily setup nested structures using native types(String, Number, Boolean, Array, Object) to enforce a certain response structure, making it almost impossible to spill properties in a response that you don't want.

A little example is shown below:

Let's say we have the following response structure

const response = {
  username: 'dawreck',
  password: '',
  todos: [
    {description: 'this is my first todo', done: true, createdAt: '1642503108'},
    {description: 'i also need to do this', done: false, createdAt: '1642503118'}
  ]
}

We then create a response schema and add it to the controller as follows:

import {StringValue} from 'nestjs-response-schema';

const schema = {
  username: StringValue,
  todos: [
    {description: StringValue, done: BooleanValue}
  ]
}
@ResponseSchema(schema)
@Get('')
getInformation() {
  return response;
}

This will enable the ResponseSchemaInterceptor to run on the response, producing the following output:

{
  "username": "dawreck",
  "todos": [
    {
      "description": "this is my first todo",
      "done": true
    },
    {
      "description": "i also need to do this",
      "done": false
    }
  ]
}

Getting Started


First, start by installing nestjs-response-schema by running the following command:

npm i nestjs-response-schema

After installing the package, include the module in your app module and register it using the register method. (This loads the module globally)

import {ResponseSchemaModule} from 'nestjs-response-schema';

@Module({
  imports: [
    ResponseSchemaModule.setup({
      // options here
    }),
  ],
})
export class AppModule {
}

Options


Currently the following options are supported

  • strictKeyCheck: boolean
  • strictTypeCheck: boolean
  • onStrictKeyCheckFail: function
  • onStrictTypeCheckFail: function

strictKeyCheck

This option allows you to enable/disable the strict key check. This checks the keys from received data against the keys from the schema. When a key that is in the schema, is missing from the data, it will throw an InternalServerException. This behavior is overridable by the onStrictKeyCheckFail option.

strictTypeCheck

This option allows you to enable/disable the strict type check. This checks the types from received data values against the types from the schema. When the data value type doesn't match the schema type, it will throw an InternalServerException. This behavior is overridable by the onStrictTypeCheckFail option.

onStrictKeyCheckFail

This option allows you to override what happens when a strict key check fails. This function receives the currently evaluated schema, data and the key that is evaluated as arguments.

onStrictTypeCheckFail

This option allows you to override what happens when a strict type check fails. This function receives the currently evaluated schema, data and the key that is evaluated as arguments.

How to use


To start using the response schema's after installing, start by annotating a controller method with the @ResponseSchema(schema, statusCode) decorator. This decorator takes a schema as the argument and an optional statusCode.

Schema's are made as objects and are constructed with key value pairs, the keys being the name of the property, and the values being the expected types. This package makes use of it's own type to handle the underlying logic. Currently the following types are supported:

  • StringValue
  • NumberValue
  • BooleanValue
  • Object
  • Array

StringValue


A StringValue represents a basic string.

Schema

import {StringValue} from 'nestjs-response-schema';

const schema = {
  name: StringValue
}

Data

const data = {
  name: 'test',
  hidden: 'hello',
}

Output

{
  "name": "test"
}

A StringValue can also be used with a function attached, allowing you to transform or aggregate data. The function received the data object with the containing key as an argument

Schema

import { StringValue } from 'nestjs-response-schema';

const schema = {
  test: StringValue((data) => data.nested.name.substr(1, 2))
}

Data

const data = {
  name: 'test',
  hidden: 'hello',
  nested: {
    name: 'hello'
  }
}

Output

{
  "test": "el"
}

NumberValue


A NumberValue represents a basic numerical value

Schema

import { NumberValue } from 'nestjs-response-schema';

const schema = {
  id: NumberValue
}

Data

const data = {
  id: 12,
  hidden: 'hello',
}

Output

{
  "id": 12
}

A NumberValue can also be used with a function attached, allowing you to transform or aggregate data. The function received the data object with the containing key as an argument

Schema

import { NumberValue } from 'nestjs-response-schema';

const schema = {
  id: NumberValue((data) => (data.nested.code + 1))
}

Data

const data = {
  id: 12,
  hidden: 'hello',
  nested: {
    code: 1234,
  }
}

Output

{
  "id": 1235
}

BooleanValue


A BooleanValue represents a basic boolean value

Schema

import { BooleanValue } from 'nestjs-response-schema';

const schema = {
  exposed: BooleanValue
}

Data

const data = {
  exposed: true,
  hidden: 'hello',
}

Output

{
  "exposed": true
}

A BooleanValue can also be used with a function attached, allowing you to transform or aggregate data. The function received the data object with the containing key as an argument

Schema

import { BooleanValue } from 'nestjs-response-schema';

const schema = {
  cool: BooleanValue((data) => data.nested.isCool)
}

Data

const data = {
  exposed: true,
  hidden: 'hello',
  nested: {
    isCool: true
  }
}

Output

{
  "cool": true
}

Object


nestjs-response-schema has supported for nested schema's and data and will automatically pick it up when it is used.

Schema

import { StringValue } from 'nestjs-response-schema';

const schema = {
  content: {
    name: StringValue
  }
}

Data

const data = {
  title: 'Hello World',
  content: {
    name: 'NestJS'
  }
}

Output

{
  "content": {
    "name": "NestJS"
  }
}

Array


nestjs-response-schema also has support for arrays and defining the schema for array items. To define an array schema, just create an array with 1 item, and have that item just like any other schema object. It will force this schema upon any item in the data array

Schema

import { StringValue } from 'nestjs-response-schema';

const schema = {
  items: [
    {name: StringValue}
  ]
}

Data

const data = {
  items: [
    {name: 'test 1', hidden: 'hello'},
    {name: 'test 2', hidden: 'hello2'},
  ]
}

Output

{
  "items": [
    {
      "name": "test1"
    },
    {
      "name": "test 2"
    }
  ]
}

NestJS/Swagger


This package will also set the @ApiResponse on the affected method with the right schema. It will by default set the response status to 200 unless specified

@ResponseSchema({}) will automatically make a Swagger Response with a 200 statusCode

Post requests in NestJS usually response with a 201 statusCode and thereof we need to response with a 201 @ResponseSchema({}, 201)

Examples