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-custom-response

v1.0.3

Published

Build custom response in multi-language

Downloads

11

Readme

{
"message": "ok", // multilingual
"data": [
  // you response data
],
"statusCode": 200
}

Installation

Install

Install the library with

$ npm install nestjs-custom-response

This package depends on the nestjs-i18n package

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";
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`