summary refs log tree commit diff
path: root/src/activitypub/util/OrderedCollection.ts
blob: 83cf9bd9135b6518d3e2f615a8aa3824b7d7148b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import {
	APObject,
	APOrderedCollection,
	OrderedCollectionItemsField,
} from "activitypub-types";
import { Request } from "express";

interface ActivityPubable {
	toAP(): APObject;
}

interface CorrectOrderedCollection extends APOrderedCollection {
	orderedItems?: OrderedCollectionItemsField[];
}

export const makeOrderedCollection = async <T extends ActivityPubable>(
	req: Request,
	id: string,
	getTotalElements: () => Promise<number>,
	getElements: (before?: string, after?: string) => Promise<T[]>,
): Promise<CorrectOrderedCollection> => {
	const { page, min_id, max_id } = req.query;

	if (!page)
		return {
			"@context": "https://www.w3.org/ns/activitystreams",
			id: id,
			type: "OrderedCollection",
			totalItems: await getTotalElements(),
			first: `${id}?page=true`,
			last: `${id}?page=true&min_id=0`,
		};

	const after = min_id ? `${min_id}` : undefined;
	const before = max_id ? `${max_id}` : undefined;

	const elems = await getElements(before, after);

	const items = elems.map((elem) => elem.toAP());

	return {
		"@context": "https://www.w3.org/ns/activitystreams",
		id: `${id}?page=true`,
		type: "OrderedCollection",
		first: `${id}?page=true`,
		last: `${id}?page=true&min_id=0`,
		totalItems: await getTotalElements(),
		orderedItems: items,
	};
};