0.0.1 • Published 2 years ago

nestjs-response v0.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

Installation

Install

Install the library with

$ npm install nestjs-custom-response

This package depends on the nestjs-i18n-2 package, which is a fork of nestjs-i18n. Therefore, you should remove npm uninstall nestjs-i18n if installed. The difference between nestjs-i18n-2 and nestjs-i18n is just that the validation error description is moved from the errors[] field to data[] to unify the API structure.

Create i18n folder in src your NestJS Project

Create 3 folders en, _code and xx in i18n folder.

project:
├───src
│   ├───i18n
│   │   ├───en
│   │   ├───_code
│   │   └───vi

Note: xx is your short-name of language, exp: vi, fr,... _code is custom for HTTP_CODE Default, this package use file response.json. So, you need to create this file on all language folders en, _code, xx,... This is file src\i18n\en\response.json content:

{
    "message": {
        "inputInvalid":"Invalid input",
        "error": "An error occurred",
        "ok": "ok",
        "successful": "Successful",
        "successfully": "Successful",
        "connectionLimit": "Connection reach limit",
        "tokenInvalid": "Token invalid",
        "requestTimeout": "Request timeout",
        "unauthorized": "Unauthorized",
        "forbiden": "Forbiden"
    }
}

And here is the translation file src\i18n\vi\response.json content:

{    
    "message": {
        "inputInvalid":"Thông tin đầu vào không đúng",
        "error": "Đã xảy ra lỗi",
        "ok": "ok",
        "successful": "Thành công",
        "successfully": "Thành công",
        "connectionLimit": "Số lượng kết nối máy chủ đạt giới hạn",
        "tokenInvalid": "Token không có hiệu lực",
        "requestTimeout": "Hết thời gian chờ",
        "unauthorized": "Không thể xác thực",
        "forbiden": "Không có quyền truy cập"
    }
}

Define Http Status Code src\i18n\_code\response.json content:

{
    "message": {
        "inputInvalid":"400",
        "error": "500",
        "ok": "200",
        "successful": "200",
        "successfully": "200",
        "connectionLimit": "429",
        "tokenInvalid": "401",
        "requestTimeout": "408",
        "unauthorized": "401",
        "forbiden": "403",
    }
}

Import i18n to AppModule:

import { Module } from '@nestjs/common';
import { I18nModule, QueryResolver, AcceptLanguageResolver } from 'nestjs-i18n-2';
import * as path from 'path';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    I18nModule.forRoot({
      fallbackLanguage: 'en',
      loaderOptions: {
        path: path.join(__dirname, '/i18n/'),
        watch: true,
      },
      resolvers: [
        { use: QueryResolver, options: ['lang'] },
        AcceptLanguageResolver,
      ],
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Update CompileOptions in root nest-cli.json:

{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "assets": [
      { "include": "i18n/**/*", "watchAssets": true }
    ]
  }
}

Usage

Use Custom Response with i18n:

in your Controller:

@Get()
  getHello(@I18n() i18n:I18nContext): string {
    let customResponse = new CustomResponseService(i18n)
    customResponse = this.appService.getHello(customResponse); // call Service Method
     throw new HttpException(customResponse, customResponse.statusCode)
  }

in your Service:

getHello(customResponse: CustomResponseService): CustomResponseService {
    customResponse.makeResponseResponse("response.message.successful", 200, {name: "vncafe"})
    return customResponse;
  }

your Response

{
  "message": "Thành công", // auto translate to my language
  "data": [
    {
      "name": "vncafe"
    }
  ],
  "statusCode": 200
}

Coffee

As a programmer, I drink coffee every morning. If you want, you can offer me a cup of coffee:

ETH (erc20): `0x17e333b82011d8507654af5fcec467860299d607`
BTC: `1FD3GgNxMXe1MeDic6Aa5MLW8FEggUAWhA`