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

case-conversion-nest

v1.0.1

Published

Case conversion for nest DTO definitions

Downloads

8

Readme

Case Conversion Nest

Node.js Package

Tool & CLI Plugin for Nest.js DTO case conversion.

This lib helps you to use snake_case in DTO and camelCase in code.

Request body:

{
  "cat_name": "xxx"
}

DTO definition:

export class CatRequestDTO {
  @IsString()
  catName: string
}

export class CatResponseDTO {
  catId: string
}

Response:

{
  "cat_id": "xxx"
}

Install

yarn add case-conversion-nest

# or

npm install case-conversion-nest

Usage

  1. Set up the global interceptor CaseConversionInterceptor in AppModule
import { Module } from '@nestjs/common'
import { APP_INTERCEPTOR } from '@nestjs/core'
import { CaseConversionInterceptor } from 'case-conversion-nest'

@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: CaseConversionInterceptor,
    },
  ],
})
export class AppModule {}
  1. Use ValidationPipe globally with transform option set to true
app.useGlobalPipes(new ValidationPipe({ transform: true }))
  1. Use CaseConversionResponse in route handlers to indicate response DTO class
import { Controller, Get } from '@nestjs/common'
import { ListCatsResponseDTO } from './list-cats.dto'
import { CaseConversionResponse } from 'case-conversion-nest'

@Controller('cats')
export class CatsController {
  @Get()
  @CaseConversionResponse(ListCatsResponseDTO)
  findAll() {
    return { /** ... */ }
  }
}
  1. Use CLI plugin in nest-cli.json
{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "plugins": [
      "@nestjs/swagger",
      {
        "name": "case-conversion-nest",
        "options": {
          "dtoFileNameSuffix": ["dto.ts", "entity.ts"]
        }
      }
    ]
  }
}

Caveats

  1. All of your DTO classes must be inside the files you specify in dtoFileNameSuffix (Defaults to dto.ts, entity.ts)
// create-cat.dto.ts
export class CreateCatDTO {
  catName: string

  nestedObject: OtherDTO
}

// other.ts
export class OtherDTO {
  /**
   * This field will not be converted as the class is not inside a dto.ts file
   * 
   * In addition, this field will not be displayed in Swagger UI
  */
  otherField: string
}
  1. Nested object must be annotated with Type decorator, or else nested object will not be converted
import { Type } from 'class-transformer'

export class CreateCatDTO {
  catName: string

  @Type(() => A)
  converted: A

  notConverted: B
}

class A {
  /**
   * Converted
  */
  aName: string
}

class B {
  /**
   * This field will not be converted
  */
  bName: string
}

How it works

When is the case conversion done

The DTO case conversion is done by class-transformer. When a request comes in, the query/payload will be transformed by ValidationPipe. Based on that, by adding @Expose({ name: 'snake_case_field' }) to DTO fields, the conversion will be done automatically.

In terms of response body, Nest.js does not have a similar "ValidationPipe" to transform it, so CaseConversionInterceptor is provided to handle it. The decorator CaseConversionResponse is also needed to indicate the response body type, because the type is not available in the interceptor internally.

Why do I need to use the cli plugin

The conversion is done by adding @Expose decorator, but it's tedious to add it to every fields manually, so the cli plugin is provided to do this work automatically.

Note that extra @Expose added manually will not be effective.

How is the fields in Swagger document converted

It's also done by the cli plugin, by adding @ApiProperty({ name: 'snake_case_field' }) to the field.

It's OK to add extra @ApiProperty because the metadata is merged by @nestjs/swagger.