nestjs-json-api-serializer
TypeScript icon, indicating that this package has built-in type declarations

0.0.0 • Public • Published

Nest Logo

A lib to NestJS to serializer JSON following the JSON Api pattern.

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"
      }
    }
  ]
}

Package Sidebar

Install

npm i nestjs-json-api-serializer

Weekly Downloads

2

Version

0.0.0

License

ISC

Unpacked Size

7.67 kB

Total Files

8

Last publish

Collaborators

  • tacnoman