]>
Commit | Line | Data |
---|---|---|
1 | import Bluebird from 'bluebird' | |
2 | import validator from 'validator' | |
3 | import { pageToStartAndCount } from '@server/helpers/core-utils' | |
4 | import { ACTIVITY_PUB } from '@server/initializers/constants' | |
5 | import { ResultList } from '@shared/models' | |
6 | ||
7 | type ActivityPubCollectionPaginationHandler = (start: number, count: number) => Bluebird<ResultList<any>> | Promise<ResultList<any>> | |
8 | ||
9 | async function activityPubCollectionPagination ( | |
10 | baseUrl: string, | |
11 | handler: ActivityPubCollectionPaginationHandler, | |
12 | page?: any, | |
13 | size = ACTIVITY_PUB.COLLECTION_ITEMS_PER_PAGE | |
14 | ) { | |
15 | if (!page || !validator.isInt(page)) { | |
16 | // We just display the first page URL, we only need the total items | |
17 | const result = await handler(0, 1) | |
18 | ||
19 | return { | |
20 | id: baseUrl, | |
21 | type: 'OrderedCollection', | |
22 | totalItems: result.total, | |
23 | first: result.data.length === 0 | |
24 | ? undefined | |
25 | : baseUrl + '?page=1' | |
26 | } | |
27 | } | |
28 | ||
29 | const { start, count } = pageToStartAndCount(page, size) | |
30 | const result = await handler(start, count) | |
31 | ||
32 | let next: string | undefined | |
33 | let prev: string | undefined | |
34 | ||
35 | // Assert page is a number | |
36 | page = parseInt(page, 10) | |
37 | ||
38 | // There are more results | |
39 | if (result.total > page * size) { | |
40 | next = baseUrl + '?page=' + (page + 1) | |
41 | } | |
42 | ||
43 | if (page > 1) { | |
44 | prev = baseUrl + '?page=' + (page - 1) | |
45 | } | |
46 | ||
47 | return { | |
48 | id: baseUrl + '?page=' + page, | |
49 | type: 'OrderedCollectionPage', | |
50 | prev, | |
51 | next, | |
52 | partOf: baseUrl, | |
53 | orderedItems: result.data, | |
54 | totalItems: result.total | |
55 | } | |
56 | } | |
57 | ||
58 | // --------------------------------------------------------------------------- | |
59 | ||
60 | export { | |
61 | activityPubCollectionPagination | |
62 | } |