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
}
]
}
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 {
}
Currently the following options are supported
- strictKeyCheck: boolean
- strictTypeCheck: boolean
- onStrictKeyCheckFail: function
- onStrictTypeCheckFail: function
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.
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.
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.
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.
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
A StringValue represents a basic string.
import {StringValue} from 'nestjs-response-schema';
const schema = {
name: StringValue
}
const data = {
name: 'test',
hidden: 'hello',
}
{
"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
import { StringValue } from 'nestjs-response-schema';
const schema = {
test: StringValue((data) => data.nested.name.substr(1, 2))
}
const data = {
name: 'test',
hidden: 'hello',
nested: {
name: 'hello'
}
}
{
"test": "el"
}
A NumberValue represents a basic numerical value
import { NumberValue } from 'nestjs-response-schema';
const schema = {
id: NumberValue
}
const data = {
id: 12,
hidden: 'hello',
}
{
"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
import { NumberValue } from 'nestjs-response-schema';
const schema = {
id: NumberValue((data) => (data.nested.code + 1))
}
const data = {
id: 12,
hidden: 'hello',
nested: {
code: 1234,
}
}
{
"id": 1235
}
A BooleanValue represents a basic boolean value
import { BooleanValue } from 'nestjs-response-schema';
const schema = {
exposed: BooleanValue
}
const data = {
exposed: true,
hidden: 'hello',
}
{
"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
import { BooleanValue } from 'nestjs-response-schema';
const schema = {
cool: BooleanValue((data) => data.nested.isCool)
}
const data = {
exposed: true,
hidden: 'hello',
nested: {
isCool: true
}
}
{
"cool": true
}
nestjs-response-schema has supported for nested schema's and data and will automatically pick it up when it is used.
import { StringValue } from 'nestjs-response-schema';
const schema = {
content: {
name: StringValue
}
}
const data = {
title: 'Hello World',
content: {
name: 'NestJS'
}
}
{
"content": {
"name": "NestJS"
}
}
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
import { StringValue } from 'nestjs-response-schema';
const schema = {
items: [
{name: StringValue}
]
}
const data = {
items: [
{name: 'test 1', hidden: 'hello'},
{name: 'test 2', hidden: 'hello2'},
]
}
{
"items": [
{
"name": "test1"
},
{
"name": "test 2"
}
]
}
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)