Public
Script
January 8, 2024
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);
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
January 8, 2024