JavaScript
NestJS 공부하기
foxlee
2022. 3. 15. 18:34
기본 개념 공부하기
- Controllers are responsible for handling incoming requests and returning responses to the client.
- Providers are a fundamental concept in Nest. Many of the basic Nest classes may be treated as a provider – services, repositories, factories, helpers, and so on.
- The main idea of a provider is that it can be injected as dependency; this means objects can create various relationships with each other, and the function of "wiring up" instances of objects can largely be delegated to the Nest runtime system.
Services
- Service will be responsible for data storage and retrieval, and is designed to be used by Controllers, so it's a good candidate to be defined as a provider.
Modules
// ./users.module.ts
@Module({
imports: [EmailModule, TypeOrmModule.forFeature([UserEntity])], // 13번에서 export한 email모듈의 provider에 있는 EmailService을 UserModule내에서 공유
controllers: [UsersController], // routes
providers: [UsersService], // Nest injector에 의해 인스턴스화되고 UsersModule 내에서 공유됨 // UserController 에서 UserService private변수로 사용
}) // * providers에 EmailService를 넣을 수도 있지만 좋지 않은 패턴/ EmailModule을 import을 해서 EmailSerivce inject
export class UsersModule {}
// ./email.module.ts
@Module({
providers: [EmailService], // Nest injector에 의해 인스턴스화되고 EmailModule 내에서 공유됨
exports: [EmailService], // export 하여 3번 줄에서 import 가능 - export하지 않으면 다른 module에서 사용하지 못함
})
export class EmailModule {}
- providers
- the providers that will be instantiated by the Nest injector and that may be shared at least across this module
- controllers
- the set of controllers defined in this module which have to be instantiated
- controllers(routes)
- imports
- the list of imported modules that export the providers which are required in this module
- exports
- the subset of providers that are provided by this module and should be available in other modules which import this module.
- JWT를 통한 인증
- TypeORM
- 특정 컬럼 제외하기(User password) + Interceptor
- Entity 컬럼에 Exclude 데코레이터 추가
- useGlobalInterceptors
- Global interceptors are used across the whole application, for every controller and every route handler. In terms of dependency injection, global interceptors registered from outside of any module (with useGlobalInterceptors()) cannot inject dependencies since this is done outside the context of any module.
./src/users/entities/user.entity.ts
import { Exclude } from 'class-transformer';
import {
BaseEntity,
Column,
Entity,
PrimaryGeneratedColumn,
Unique,
} from 'typeorm';
@Entity({ name: 'users' })
@Unique(['name'])
export class UserEntity extends BaseEntity {
// ~~ 다른 컬럼들 ~~
@Exclude()
@Column()
password: string;
}
// 방법1 전역에서 설정하기
./main.ts
// ~~ 환경 설정
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(
new ClassSerializerInterceptor(app.get(Reflector)),
);
await app.listen(3000);
}
bootstrap();
// 방법2 특정 컨트롤러/엔드포인트에서만 적용하기
@UseInterceptors(ClassSerializerInterceptor) // 방법 2-1
@Controller('users')
export class UsersController {}
@UseInterceptors(ClassSerializerInterceptor) // 방법 2-2
@Get()
findAll() {
return this.usersService.findAll();
}
참고 링크