Advanced Node.js Interview QuestionsAdvancedScenario
Node.js · Question 90
How would you design a REST API for interview topics in Express?
Direct answer
Mount /interviews/topics router with GET list (pagination query), GET :slug detail, validate params, thin controllers calling service layer, JSON errors, express.json middleware, and 404/500 handlers — map same design to Fastify for AceDevHub production.
Scenario: build read-only public API for interview topic pages — mirrors GET /interviews/topics/:slug in AceDevHub.
- Routes — GET /interviews/topics, GET /interviews/topics/:slug.
- Middleware stack — cors, helmet, rate-limit, express.json (Q42–48).
- Service layer — interviewsService.getTopicPage(slug) with pg query.
- Errors — 404 unknown slug; 500 with generic message.
scenario-rest-api.mjs
import express from "express";
const app = express();
app.use(express.json());
const router = express.Router();
router.get("/", async (req, res, next) => {
try {
const page = Number(req.query.page ?? 1);
const topics = await interviewsService.listTopics({ page, limit: 20 });
res.json({ data: topics });
} catch (err) { next(err); }
});
router.get("/:slug", async (req, res, next) => {
try {
const topic = await interviewsService.getTopicPage(req.params.slug);
if (!topic) return res.status(404).json({ error: { code: "NOT_FOUND" } });
res.json({ data: { page: topic } });
} catch (err) { next(err); }
});
app.use("/interviews/topics", router);