Repository
Repository는 Infra 레이어에서 Dto를 기반으로 Database에 쿼리하기 위해 사용합니다.
Dto를 기반으로 Query하는 경우 다음과 같습니다.
- 일부 데이터만 쿼리해야 하는 경우
- Slow Query를 방지하기 위해 필요한 데이터만 쿼리에서 직접
JOIN하는 경우 - Pagination을 적용하는 경우
Usage
예를 들어 A 라우터에서는 사용자가 소속된 회사 정보가 노출되어야 하지만 B 라우터에서는 해당 정보를 필요로 하지 않을때 반환값을 두개의 Dto로 나누어 동일한 쿼리에서 exportTo로 Attribute를 나누어 처리합니다.
A 라우터에 대한 Dto에는 아래와 같이 구성되고,
class ARouterDto extends ExtendableDto {
@TypeIs.INT({ comment: "아이디" })
id: number;
@TypeIs.STRING({ comment: "이름" })
name: number;
@TypeIs.DTO({ dto: CompanyDto, as: "company", comment: "회사 정보" })
company: CompanyDto;
}
B 라우터에 대한 `Dto는 아래와 같이 구성됩니다.
class ARouterDto extends ExtendableDto {
@TypeIs.INT({ comment: "아이디" })
id: number;
@TypeIs.STRING({ comment: "이름" })
name: number;
}
위처럼 필요한 정보에 따라 적절하게 DTO를 구성하여 Repository를 개발하면 Query 부하를 자연스럽게 해결하며 개발의 효율성이 높아지고, 개별 라우터에 대한 요청/반환값을 손쉽게 파악할 수 있습니다.
Full Example
import { Repository, PaginationQueryDto } from "@asapjs/sequelize";
import UsersTable from "@user/domain/entity/UsersTable";
class UserTableRepository extends Repository {
public users: typeof UsersTable;
constructor() {
this.users = UsersTable;
}
public getUserInfoById = async (id: number) => {
const raw = await this.repository.findOne(this.users, {
exportTo: UserInfoDto,
where: { id },
});
if (!raw) return null;
return new UserInfoDto().map(raw);
};
public getAdminUserInfoById = async (id: number) => {
const raw = await this.repository.findOne(this.users, {
exportTo: AdminUserInfoDto,
where: { id },
});
if (!raw) return null;
return new AdminUserInfoDto().map(raw);
};
public getUserList = async (paging: PaginationQueryDto) => {
const raw = await this.repository.findOne(this.users, {
exportTo: UserInfoDto,
paging,
});
if (!raw) return null;
return new UserInfoDto().map(raw);
};
}