Readme

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:

const 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.

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!
v5
January 8, 2024