nestjs-json-api-serializer
v0.0.0
Published
Nestjs serializer to use with jsonapi.org pattern
Downloads
3
Maintainers
Readme
Installation
Run in your terminal
$ npm install --save @nestjs-modules/json-api-serializer
or via yarn
$ yarn add @nestjs-modules/json-api-serializer
Getting started
import {
Controller,
Get,
UseInterceptors,
} from '@nestjs/common';
import { JsonApiInterceptor } from '@nestjs-modules/json-api-serializer';
@Controller('v1/cats')
export class CatsController {
@UseInterceptors(JsonApiInterceptor)
@Get()
async index() {
return {
data: [ /* my array of objects */ ],
};
}
}
When you make a curl to http://localhost/v1/cats
the JsonApiInterceptor
will change your payload following the JSON Api pattern.
{
"data": [
{
"id": 2,
"attributes": {
"color": "orange",
"name": "Shadow",
"genre": "male"
},
"relations": {
"power": {
"id": 33,
"attributes": {
"powerName": "meow"
}
}
}
},
{
"id": 12,
"attributes": {
"color": "brown",
"name": "british",
"genre": "female"
},
"relations": {
"power": {
"id": 34,
"attributes": {
"powerName": "purr"
}
}
}
}
]
}
Fields
Following the JSON Api fields pattern, if you pass a queryString called fields
you can get only fields listed.
Example: http://localhost:3000/v1/cats?fields=color,name
the result should be:
{
"data": [
{
"id": 2,
"attributes": {
"color": "orange",
"name": "Shadow"
}
},
{
"id": 12,
"attributes": {
"color": "brown",
"name": "british"
}
}
]
}