Skip to Content
BackendNestJs21-Pagination-Page Pagination

1. DTO에 Page 프로퍼티 추가

paginatePosts()를 2가지 함수로 나눌 것이다.

  • pagePaginatePosts
  • cursorPaginatePosts
posts.service.ts
1
// posts.service.ts 생략
2
/***
3
* 1) 오름차순으로 정렬하는 pagination만 구현한다
4
*/
5
async paginatePosts(dto: PaginatePostDto) {
6
if (dto.page) {
7
return this.pagePaginatePosts(dto)
8
} else {
9
return this.cursorPaginatePosts(dto)
10
}
11
}
12
13
/*** 페이지 기반 페이지네이션
14
* data: Data[],
15
* total: number
16
*/
17
async pagePaginatePosts(dto: PaginatePostDto) {}
18
19
/*** 커서 기반 페이지네이션
20
*
21
*/
22
async cursorPaginatePosts(dto: PaginatePostDto) {
23
const where: FindOptionsWhere<PostsModel> = {}
24
25
if (dto.where__id_less_than) {
26
where.id = LessThan(dto.where__id_less_than)
27
} else if (dto.where__id_more_than) {
28
where.id = MoreThan(dto.where__id_more_than)
29
}
30
31
const posts = await this.postsRepository.find({
32
where,
33
order: {
34
createdAt: dto.order__createAt,
35
},
36
take: dto.take,
37
})
38
39
/****
40
* 해당되는 포스트가 0개 이상이면, 마지막 포스트를 가져오고
41
* 아니면 null을 반환한다.
42
*/
43
const lastItem = posts.length > 0 && posts.length === dto.take ? posts[posts.length - 1] : null
44
const nexttUrl = lastItem && new URL(`${PROTOCOL}://${HOST}/posts`)
45
46
/**** dto의 키값들을 루핑하면서
47
* 키값에 해당되는 벨류가 존재하면, parame에 그대로 붙여넣는다.
48
* 단, where__id_more_than 값만 lastItem의 마지막 값으로 넣어준다.
49
*/
50
if (nexttUrl) {
51
for (const key of Object.keys(dto)) {
52
if (dto[key]) {
53
if (key !== 'where__id_more_than' && key !== 'where__id_less_than') {
54
nexttUrl.searchParams.append(key, dto[key])
55
}
56
}
57
}
58
let key = null
59
if (dto.order__createAt === 'ASC') {
60
key = 'where__id_more_than'
61
} else {
62
key = 'where__id_less_than'
63
}
64
nexttUrl.searchParams.append(key, lastItem.id.toString())
65
}
66
67
/*** Response
68
* data : Data[],
69
* cursor : {
70
* after: 마지막 Data의 ID
71
* }
72
* count: 응답한 데이터의 개수
73
* next: 다음 요청을 할 떄 사용할 URL
74
*/
75
return {
76
data: posts,
77
cursor: {
78
after: lastItem?.id ?? null,
79
},
80
count: posts.length,
81
nest: nexttUrl?.toString() ?? null,
82
}
83
}

그리고 paginate-post.dto에 page 프로퍼티를 추가해야 한다.

paginate-post.dto.ts
1
// 생략
2
export class PaginatePostDto {
3
@IsNumber()
4
@IsOptional()
5
page?: number
6
7
// 생략
8
}

2. Post 응답 생성

posts.service.ts
1
// posts.service.ts 생략
2
/*** 페이지 기반 페이지네이션
3
* data: Data[],
4
* total: number
5
*/
6
async pagePaginatePosts(dto: PaginatePostDto) {
7
const posts = await this.postsRepository.find({
8
skip: dto.take * (dto.page - 1), // 1페이지부터 시작하도록
9
take: dto.take,
10
order: {
11
createdAt: dto.order__createAt,
12
},
13
})
14
15
return {
16
data: posts,
17
}
18
}

3. 응답에 total 프로퍼티 추가

posts.service.ts
1
// posts.service.ts 생략
2
/*** 페이지 기반 페이지네이션
3
* data: Data[],
4
* total: number
5
*/
6
async pagePaginatePosts(dto: PaginatePostDto) {
7
const [posts, count] = await this.postsRepository.findAndCount({
8
skip: dto.take * (dto.page - 1), // 1페이지부터 시작하도록
9
take: dto.take,
10
order: {
11
createdAt: dto.order__createAt,
12
},
13
})
14
15
return {
16
data: posts,
17
total: count,
18
}
19
}