File size: 3,505 Bytes
1a25764
 
 
ad871c9
 
1a25764
e9d5bbe
1f0f638
 
ad871c9
1a25764
 
 
e9d5bbe
1a25764
ad871c9
 
 
 
 
 
 
1a25764
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad871c9
9e8da7a
 
1a25764
 
cfbebe0
 
 
 
 
ad871c9
cfbebe0
 
 
 
 
 
ad871c9
cfbebe0
 
 
 
9e8da7a
2e6d0d7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
'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 };