TIL
3월3일 - TypeORM에서의 pagination (limit, offset)
포시
2023. 3. 3. 11:28
728x90
개요
Nest.js에서 TypeORM을 쓰며 pagination(페이지네이션)을 구현하게 되어
새로 알게된 부분을 정리해보았다.
Basic Repository
async findAllUsers({ id, page }: FindAllUserInput): Promise<FindAllUserOutput> {
// ...생략
const allUsers = await this.users.find({
where: { id },
take: 10,
skip: (page - 1) * 10,
});
// ...생략
}
기본 Repository를 쓸 경우에 find를 쓰면서 where 처럼
take, skip을 써서 pagination을 구현하는 경우이다.
- take: 한 번에 보여줄 개수 - mysql에서의 limit을 생각하면 된다.
- skip: 말 그대로 몇 개를 건너뛰고 보여줄건지 - mysql에서의 offset을 생각하면 된다.
Custom Repository
async getMeetups(page: number): Promise<Meetup[]> {
return await this.createQueryBuilder()
.select()
.take(10)
.skip((page - 1) * 10)
.getMany();
}
Custom Repository에서 createQueryBuilder를 쓸 경우에도
위와 같이 사용할 수 있다.
가져오는 값 10에 대해서는 하드코딩하지 않고 따로 빼
config 값으로 사용한다면 더 좋을 것이다.
참고한 곳
https://www.kindacode.com/snippet/pagination-in-typeorm-find-options-querybuilder/
Pagination in TypeORM (Find Options & QueryBuilder) - Kindacode
This short and straight-to-the-point article shows you how to paginate data in TypeORM. Using Find(), FindAndCount() methods If you use a find method, you
www.kindacode.com
https://velog.io/@outclassstudio/NestJS-TypeORM-Pagination
NestJS + TypeORM : Pagination
Nest와 TypeORM으로 매우 간단하게 페이지네이션을 구현해보자
velog.io
728x90