$ nest g service [name]
providers
로 선언된 JS 클래스// interface/cat.interface.ts
export interface Cat {
name: string;
age: number;
breed: string;
}
// cats.service.ts
import { Injectable } from '@nestjs/common';
import { Cat } from './interfaces/cat.interface';
@Injectable()
export class CatsService {
private readonly cats: Cat[] = [];
create(cat: Cat) {
this.cats.push(cat);
}
findAll(): Cat[] {
return this.cats;
}
}
// cats.controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';
@Controller('cats')
export class CatsController {
constructor(private catsService: CatsService) {}
@Post()
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}
}
constructor(private catsService: CatsService) {}
@Injectable()
데코레이터의 scope
속성 사용REQUEST
개체 삽입, GraphQL의 경우 CONTEXT
삽입)import { Injectable, Scope } from '@nestjs/common';
@Injectable({ scope: Scope.REQUEST })
export class CatsService {
constructor(@Inject(REQUEST) private request: Request) {}
}
ControllerOptions
객체의 scope
속성 사용@Controller({
path: 'cats',
scope: Scope.REQUEST,
})
export class CatsController {}
https://docs.nestjs.kr/fundamentals/custom-providers
@Optional()
데코레이터 사용import { Injectable, Optional, Inject } from '@nestjs/common';
@Injectable()
export class HttpService<T> {
constructor(@Optional() @Inject('HTTP_OPTIONS') private httpClient: T) {}
}
@Inject()
데코레이터 사용import { Injectable, Inject } from '@nestjs/common';
@Injectable()
export class HttpService<T> {
@Inject('HTTP_OPTIONS')
private readonly httpClient: T;
}
@Module()
데코레이터 내에 providers
배열에 해당 서비스 포함// app.module.ts
import { Module } from '@nestjs/common';
import { CatsController } from './cats/cats.controller';
@Module({
controllers: [CatsController],
providers: [CatsService],
})
export class AppModule {}