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'
7 type ActivityPubCollectionPaginationHandler = (start: number, count: number) => Bluebird<ResultList<any>> | Promise<ResultList<any>>
9 async function activityPubCollectionPagination (
11 handler: ActivityPubCollectionPaginationHandler,
13 size = ACTIVITY_PUB.COLLECTION_ITEMS_PER_PAGE
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)
21 type: 'OrderedCollectionPage',
22 totalItems: result.total,
23 first: result.data.length === 0
29 const { start, count } = pageToStartAndCount(page, size)
30 const result = await handler(start, count)
32 let next: string | undefined
33 let prev: string | undefined
35 // Assert page is a number
36 page = parseInt(page, 10)
38 // There are more results
39 if (result.total > page * size) {
40 next = baseUrl + '?page=' + (page + 1)
44 prev = baseUrl + '?page=' + (page - 1)
48 id: baseUrl + '?page=' + page,
49 type: 'OrderedCollectionPage',
53 orderedItems: result.data,
54 totalItems: result.total
58 // ---------------------------------------------------------------------------
61 activityPubCollectionPagination