NestJS์์ @Module()์ ๊ด๋ จ๋ ๊ตฌ์ฑ ์์(Controller, Provider ๋ฑ)๋ฅผ ํ๋๋ก ๋ฌถ๋ ๋จ์์ ๋๋ค. ํ๋์ ๊ธฐ๋ฅ(ํน์ ๋๋ฉ์ธ)์ ๋ ๋ฆฝ์ ์ผ๋ก ๊ด๋ฆฌํ ์ ์๋ ์ปจํ ์ด๋์ ๋๋ค.
@Module({
imports: [],
controllers: [UserController],
providers: [UserService, UserRepository],
exports: [UserService], // ๋ค๋ฅธ ๋ชจ๋์์ ์ฌ์ฉํ ์ ์๋๋ก ์ธ๋ถ์ ๋
ธ์ถ
})
export class UserModule {}
Provider๋ NestJS์์ ์ธ์คํด์ค๋ฅผ ๋ง๋ค์ด ๊ด๋ฆฌํ๋ ๊ฐ์ฒด์ ๋๋ค. ์ผ๋ฐ์ ์ผ๋ก ์๋น์ค(@Injectable()), ๋ฆฌํฌ์งํ ๋ฆฌ, ํฌํผ ํด๋์ค ๋ฑ์ด ์ด์ ํด๋นํฉ๋๋ค.
ํ์
์์ ์ค๋ช
ํด๋์ค Provider UserService ์ผ๋ฐ์ ์ธ ์์กด์ฑ
๊ฐ(Value) Provider useValue ์ค์ ๊ฐ์ฒด ๋ฑ
ํฉํ ๋ฆฌ Provider useFactory ๋์ ์์ฑ, ์ธ๋ถ ์กฐ๊ฑด ๊ธฐ๋ฐ
๊ธฐ์กด Provider ์ฌ์ฌ์ฉ useExisting ๊ธฐ์กด ๊ฒ ์ฌํ์ฉ
@Injectable()
export class UserService {
constructor(private readonly userRepository: UserRepository) {}
}
const ConfigProvider = {
provide: 'CONFIG',
useValue: {
port: 3000,
database: 'dev',
},
};
constructor(@Inject('CONFIG') private readonly config) {}
exports๋ ํ์ฌ ๋ชจ๋ ๋ด์ Provider๋ฅผ ๋ค๋ฅธ ๋ชจ๋์์ ์ฌ์ฉํ ์ ์๋๋ก ๋ ธ์ถํ๋ ์ญํ ์ ํฉ๋๋ค. exports์ ๋ฑ๋ก๋์ง ์์ผ๋ฉด ๋ค๋ฅธ ๋ชจ๋์์ ์ฌ์ฉ ๋ถ๊ฐ๋ฅํฉ๋๋ค.
controllers๋ exportsํ ์ ์์ต๋๋ค.
์ค์ง providers ๋๋ imports๋ ๋ชจ๋์ exports๋ง export ๊ฐ๋ฅ.
user.module.ts
@Module({
providers: [UserService],
exports: [UserService],
})
export class UserModule {}
auth.module.ts
@Module({
imports: [UserModule],
})
export class AuthModule {
constructor(private readonly userService: UserService) {}
}
NestJS ๊ตฌ์ฑ ์์ ์ํคํ
์ฒ ์ญํ
Module: ๊ธฐ๋ฅ ๋จ์์ ๊ฒฝ๊ณ, Bounded Context
Provider: ๋๋ฉ์ธ ์๋น์ค, ์ธํ๋ผ ์ด๋ํฐ, ์ ์ค์ผ์ด์ค
Export: ๋ชจ๋ ๊ฐ ๋ช
์์ ์์กด์ฑ ๊ณ์ฝ (Interface/Port ๊ฐ๋
)
ํ
์คํธ ๋์ ๊ณ์ธต ํ
์คํธ ์ ํ
Provider (Service ๋ฑ) Application, Domain ์ ๋ ํ
์คํธ (Mock ์ฌ์ฉ)
Module ์ ์ฒด Application Layer ํตํฉ ํ
์คํธ
Controller Interface Layer e2e ํ
์คํธ / HTTP ํ
์คํธ
์์ ์ค๋ช
์์
Module: NestJS์ ๊ธฐ๋ฅ ๋จ์ ๊ฒฝ๊ณ์ UserModule, AuthModule ๋ฑ
Provider: NestJS DI ์ปจํ
์ด๋์ ์ํด ๊ด๋ฆฌ๋๋ ์ธ์คํด์ค UserService, LoggerService ๋ฑ
Exports: ๋ค๋ฅธ ๋ชจ๋์์ Provider๋ฅผ ์ฌ์ฉํ ์ ์๋๋ก ๊ณต๊ฐ exports: [UserService]