반응형

In NestJS, providers are a fundamental concept of the Dependency Injection (DI) system.

Providers are classes or values that are defined within the module and can be injected into other classes

(components, controllers, other providers) within the same module or in other modules.

 

In other words, providers are objects or functions that can be injected into other objects or functions to provide them with some functionality or data. Providers are used to manage the dependencies of your application and to promote code reuse by allowing you to define and share common services across multiple components or modules.

 

To define a provider in NestJS, you need to use the @Injectable() decorator.

This decorator tells the NestJS DI system that the class can be injected into other classes as a dependency.

Once a provider is defined, it can be injected into other classes using the constructor() function.

Here's an example of a simple provider:

 

@Injectable()
export class LoggerService {
  log(message: string) {
    console.log(message);
  }
}

 

 

In this example, the LoggerService class is defined as a provider using the @Injectable() decorator.

This means that it can be injected into other classes that require a logging service.

The log() method can be called to log a message to the console.

To use this provider in another class, you can inject it in the constructor like this:

@Injectable()
export class MyService {
  constructor(private readonly logger: LoggerService) {}

  doSomething() {
    this.logger.log('Doing something...');
  }
}

In this example, the MyService class injects the LoggerService provider in the constructor.

The doSomething() method can then call the log() method of the logger to log a message.

 

Providers are a powerful feature of NestJS that allow you to build modular and reusable applications.

반응형

Nest..js req.user 오류

Nest js를 활용하여 Jwt 토큰을 발급받고 인증하는 과정을 공부하던 중에

req.user에 오류가 발생했다.

 

타입스크립트 passport 라이브러리를 다시 설치하고 다른 코드에 잘못 쓴게 있는지 한참을 찾아봤는데

도통 원인을 발견할 수 없었다.

 

 

https://stackoverflow.com/questions/64234974/ts2339-property-user-does-not-exist-on-type-request

 

TS2339: Property 'user' does not exist on type 'Request'

I am trying to use JwtAuthGuard to distinguish authenticated requests from the unauthenticated ones. I did follow the official Nestjs documentation on authentification, yet, I can't make it work as...

stackoverflow.com

 

그러다 위 글을 보고 문제를 해결했다.

req: Request로 타입을 지정해줬는데

Request를 import 하지 않아 어떤 타입인지 읽지 못해

req.user를 읽을 수 없던 것이었다.

 

import { Request } from 'express';

를 추가해주니 문제가 해결되었다.

 

 

 

반응형

If class-validator is not working in your Nest.js application, there are a few things you can try:

  1. Ensure that you have installed the class-validator package by running npm install class-validator or yarn add class-validator.
  2. Ensure that you have imported the ValidationPipe from the @nestjs/common package and added it to the main.ts file in your application. The ValidationPipe will automatically use class-validator to validate incoming requests. Here's an example of what the main.ts file might look like:
  3. javascriptCopy code
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}
bootstrap();

4. Ensure that you have added the @UsePipes decorator to your controller methods that need validation. Here's an example of how you might use the @UsePipes decorator:In this example, the @UsePipes decorator is used to apply the ValidationPipe to the create method of the CatsController. The ValidationPipe will automatically validate the catRequestDto parameter using the validation rules defined in the CatRequestDto class.

 

5.lessCopy code

import { Controller, Post, UsePipes, Body } from '@nestjs/common';
import { CatRequestDto } from './dto/cat-request.dto';
import { ValidationPipe } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Post()
  @UsePipes(new ValidationPipe())
  async create(@Body() catRequestDto: CatRequestDto) {
    // code to create a new cat
  }
}​

I hope these tips help resolve your issue with class-validator in your Nest.js application. If you're still having trouble, feel free to provide more details and I'll do my best to assist you further.

반응형

Nest.js 프레임워크를 설치하면 자동으로 eslintrc, prettierrc 파일이 따라온다.

 

eslint와 prettier은 코드 컨벤션을 유지하기 위해 코드를 포맷팅해주고,

설정된 코드 컨벤션에 위반되는 코드가 존재하면 빨간줄을 그어 경고를 한다.

 

 

1. 들여쓰기 4칸으로 설정

나는 평소에 vscode에서 들여쓰기를 할 때 4칸을 띄우는 세팅을 이용하는데

eslint와 prettier의 기본 세팅은 2칸을 띄우는 걸 적용하여 4칸을 띄우면 빨간줄을 띄운다.

 

4칸을 띄우는 걸 기본 세팅으로 바꾸려면 .prettierrc 파일에 "tabWidth" : 4 를 추가하면 된다.

{
    "singleQuote": true,
    "tabWidth": 4,
    "trailingComma": "all"
}

 

여기서 탭 정렬을 몇칸으로 설정할 건지는 하단의 링크를 보고 따라하면 된다.

https://dubaiyu.tistory.com/180

 

Visual Studio 탭정렬 tab

코드를 시각적으로 잘보이게하기위해 들여쓰기가 항상필요하다. 간혹 탭버튼을 눌렀으나 스페이스바로 들여쓰기가 되어있는경우가있는데 스페이스바의경우 들여쓰기보다 메모리가 더든다고

dubaiyu.tistory.com

 

 

 

2. 괄호 내부 띄어쓰기

eslint, prettier 괄호 내부 띄어쓰기 허용

초기 세팅에서는 괄호 안에 그냥 띄어쓰기를 쓰면 위와 같이 빨간줄을 그어서 신경이 쓰인다.

 

괄호 내부 띄어쓰기를 허용하려면

"prettier/prettier": ["error", { "endOfLine": "off" }] 

위 코드를 .eslintrc.js에 추가해주면 된다.

 

 

.eslintrc.js

module.exports = {
    parser: "@typescript-eslint/parser",
    parserOptions: {
        project: "tsconfig.json",
        tsconfigRootDir: __dirname,
        sourceType: "module",
    },
    plugins: ["@typescript-eslint/eslint-plugin"],
    extends: [
        "plugin:@typescript-eslint/recommended",
        "plugin:prettier/recommended",
    ],
    root: true,
    env: {
        node: true,
        jest: true,
    },
    ignorePatterns: [".eslintrc.js"],
    rules: {
        "prettier/prettier": ["error", { "endOfLine": "off" }],
        "@typescript-eslint/interface-name-prefix": "off",
        "@typescript-eslint/explicit-function-return-type": "off",
        "@typescript-eslint/explicit-module-boundary-types": "off",
        "@typescript-eslint/no-explicit-any": "off",
    },
};

+ Recent posts