1. service 등에서 schema 의존성 주입
- DB Query를 계층에서 사용하기 위해서는 이 또한 당연히 의존성 주입을 해주어야 한다.
1. service 계층
@Injectable()
export class CatsService {
constructor(@InjectModel(Cat.name) private readonly catModel: Model<Cat>) {}
getCats(): string {
return 'hello cats';
}
async signup(body: CatRequestDto) {
const { email, name, password } = body;
const isCatExist = await this.catModel.exists({ email });
if (isCatExist) {
throw new UnauthorizedException('해당하는 고양이는 이미 존재합니다.');
}
const hashPassword = await bcrypt.hash(password, 10);
const cat = await this.catModel.create({ email, name, password: hashPassword });
return cat.readOnlyDATA;
}
}
2. module 게층
@Module({
imports: [MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }])],
controllers: [CatsController],
providers: [CatsService],
exports: [CatsService],
})
- 위 코드처럼 의존성 주입을 위한 class 내부에서 constructor를 이용해서 의존성 주입을 해줄 수 있다. 이때, model의 타입은 사용하고자 하는 schema의 class로 한다.
- 의존성 주입은 module 단에서도 함께 해주어야만 한다.
2. response용 parameter 생성의 필요성
- Client 단에 DB query문에 따른 결과를 있는 그대로 response로 전달할 경우, 공개가 민감한 정보까지 함께 전달될 수 있기 때문이다.
- 비즈니스 로직 단에서 response로 보낼 데이터들을 일일이 변수에 할당할 수 있으나, 이는 하드코딩으로, 재사용성이 지극히 낮기 때문이다.
3. virtual field와 readonly 변수 지정을 통한 response용 parameter 지정
1. cats.schema.ts
export class Cat extend Document {
readonly readOnlyDATA: { email: string; name: string };
}
export const CatSchema = SchemaFactory.createForClass(Cat);
CatSchema.virtual('readOnlyDATA').get(function (this: Cat) {
return {
email: this.email,
name: this.name,
};
});
----------------------------------------------
2. cats.service.ts
...
const cat = await this.catModel.create({ email, name, password: hashPassword });
return cat.readOnlyDATA;
- 위와 같이, schema에서 response용 parameter를 생성하고, 이를 service에서 return 값으로 controller에 전달하는 방식으로 response를 보내면 보안을 더 챙길 수 있다.