Skip to content

Instantly share code, notes, and snippets.

@felladrin
Last active February 14, 2023 20:02
Show Gist options
  • Save felladrin/6cd078bc2b41c9c00002c7f540bab14d to your computer and use it in GitHub Desktop.
Save felladrin/6cd078bc2b41c9c00002c7f540bab14d to your computer and use it in GitHub Desktop.
Example of a pagination middleware using 'node-fetch' and 'restana'.
import fetch from "node-fetch";
import restana from "restana";
const service = restana();
const pageSize = process.env.PAGE_SIZE ? parseInt(process.env.PAGE_SIZE) : 5;
const port = process.env.PORT ? parseInt(process.env.PORT) : 3000;
const topStoriesResponse = await fetch(
"https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"
);
const topStories = (await topStoriesResponse.json()) as number[];
service.get("/page/:id", (request, response) => {
const topStoriesStartIndex = parseInt(request.params.id) * pageSize;
const topStoriesEndIndex = topStoriesStartIndex + pageSize;
const pageContent = topStories.slice(
topStoriesStartIndex,
topStoriesEndIndex
);
response.send(pageContent);
});
console.log(`Server started on port ${port}.`);
service.start(port);
{
"name": "hacker-news-pagination",
"version": "1.0.0",
"private": "true",
"type": "module",
"scripts": {
"start": "tsx watch index.ts"
},
"devDependencies": {
"node-fetch": "^3.3.0",
"restana": "^4.9.7",
"tsx": "^3.12.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment