dangkhoa2016's picture
feat: add runtime configuration for rate limiting and Redis
e9d5bbe
Raw History Blame
3.51 kB
'use strict';
const http = require('http');
const fs = require('fs');
const path = require('path');
const { port, redisOpts, rateLimitEnabled, rateLimitMax, rateLimitWindowMs, rateLimitWindowSec } = require('../config');
const RedisClient = require('../redis');
const { createRateLimiter } = require('../middleware/rate-limiter');
const createRouter = require('./route');
const redis = new RedisClient(redisOpts);
const rateLimiter = createRateLimiter(redis, { enabled: rateLimitEnabled, max: rateLimitMax, windowMs: rateLimitWindowMs });
const faviconIco = fs.readFileSync(path.join(__dirname, '..', 'public', 'favicon.ico'));
const faviconPng = fs.readFileSync(path.join(__dirname, '..', 'public', 'favicon.png'));
const { requestHandler, resetAuthCache } = createRouter(rateLimiter, faviconIco, faviconPng, redis);
const server = http.createServer(requestHandler);
(async () => {
try {
await redis.connect();
await redis.ping();
console.log('[Redis] Connected βœ“');
} catch (e) {
console.warn('[Redis] Unavailable β€” rate limiting falls back to in-memory:', e.message);
}
startServer();
})();
function printLog() {
const rlText = ` Rate limit: ${rateLimitMax} req / ${rateLimitWindowSec}s (${redis.connected ? 'Redis' : 'Memory'})`.padEnd(50);
console.log(`
╔══════════════════════════════════════════════════╗
β•‘ nodejs-json-api-server v1.0.0 β•‘
╠══════════════════════════════════════════════════╣
β•‘ http://localhost:${port}${' '.repeat(31 - String(port).length)}β•‘
β•‘ β•‘
β•‘ Endpoints: β•‘
β•‘ GET /api/users β•‘
β•‘ GET /api/users/:id β•‘
β•‘ GET /api/users/:id/posts β•‘
β•‘ GET /api/posts β•‘
β•‘ GET /api/posts/:id β•‘
β•‘ GET /api/posts/:id/comments β•‘
β•‘ GET /api/comments β•‘
β•‘ GET /api/albums β•‘
β•‘ GET /api/albums/:id/photos β•‘
β•‘ GET /api/photos β•‘
β•‘ GET /api/todos β•‘
β•‘ POST/PUT/PATCH/DELETE on any resource β•‘
β•‘ GET /health β•‘
β•‘ β•‘
β•‘${rlText}β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
`.trim());
}
function startServer() {
if (process.env.START_SERVER !== 'false') {
server.listen(port, printLog);
}
}
function closeServer() {
return new Promise((resolve) => {
server.close(resolve);
});
}
async function shutdown(signal) {
console.log(`\n[Server] ${signal} received β€” shutting down gracefully...`);
await closeServer();
try { await redis.quit(); } catch { /* ignore */ }
process.exit(0);
}
if (process.listenerCount('SIGINT') === 0) {
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
}
module.exports = { server, requestHandler, printLog, closeServer, resetAuthCache };