Last active
February 14, 2023 20:02
-
-
Save felladrin/6cd078bc2b41c9c00002c7f540bab14d to your computer and use it in GitHub Desktop.
Example of a pagination middleware using 'node-fetch' and 'restana'.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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