Return a paginated response

A helper function to take an array and return a paginated response. This is useful when defining one's own folders for pomdtr's vscode extension.

Usage:

Create valconst data = [...] export default async function(req: Request): Promise<Response> { return paginatedResponse(req, data); }

For demo usage in the context of the vscode extension see this val.

Readme
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
export async function paginatedResponse(req: Request, data: any[], defaultLimit: number = 20): Promise<Response> {
const url = new URL(req.url);
const searchParams = Object.fromEntries(url.searchParams.entries());
const limit = parseInt(searchParams.limit) || defaultLimit;
const offset = parseInt(searchParams.offset) || 0;
const dataSubset = data.slice(offset, offset + limit);
const nextPageOffset = offset + limit;
const nextPageUrl = new URL(url.toString());
nextPageUrl.searchParams.set("offset", nextPageOffset.toString());
const res = {
data: dataSubset,
links: {
self: url,
next: nextPageOffset < data.length ? nextPageUrl.toString() : null,
},
};
return Response.json(res);
}
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.