File size: 8,547 Bytes
1a25764
 
 
 
 
9e8da7a
1a25764
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e8da7a
 
1a25764
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e8da7a
1a25764
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e8da7a
 
 
1a25764
 
 
 
9e8da7a
 
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
'use strict';

const http = require('http');

const { port, redisOpts, rateLimitMax, rateLimitEnabled,
  rateLimitWindowMs, rateLimitWindowSec, maxBodySize } = require('./config');
const RedisClient = require('./redis');
const { createRateLimiter } = require('./rate-limiter');
const db = require('./database');

const redis = new RedisClient(redisOpts);

const rateLimiter = createRateLimiter(redis);

(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 json(res, status, data) {
  const body = JSON.stringify(data, null, 2);
  res.writeHead(status, {
    'Content-Type': 'application/json; charset=utf-8',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    'X-Powered-By': 'json-api-server/1.0',
  });
  res.end(body);
}

function notFound(res, msg = 'Not Found') {
  json(res, 404, { error: msg });
}

function badRequest(res, msg = 'Bad Request') {
  json(res, 400, { error: msg });
}

const BODY_TOO_LARGE = Symbol('BODY_TOO_LARGE');

function readBody(req, res) {
  return new Promise((resolve, reject) => {
    let body = '';
    req.on('data', (chunk) => {
      body += chunk;
      if (body.length > maxBodySize) {
        json(res, 413, { error: 'Request body too large', message: `Body exceeds ${maxBodySize} bytes limit` });
        req.destroy();
        reject(BODY_TOO_LARGE);
      }
    });
    req.on('end', () => {
      try {
        resolve(body ? JSON.parse(body) : {});
      } catch (_) {
        reject(new Error('Invalid JSON'));
      }
    });
    req.on('error', reject);
  });
}

function parseRoute(pathname) {
  const parts = pathname.replace(/^\/+|\/+$/g, '').split('/');
  if (parts[0] === 'api') parts.shift();

  const [table, rawId, sub] = parts;
  const id = rawId ? parseInt(rawId, 10) : null;

  if (!db.TABLES.includes(table)) return null;
  if (rawId && isNaN(id)) return null;

  return { table, id, sub };
}

const NESTED = {
  users: { posts: 'userId', albums: 'userId', todos: 'userId' },
  posts: { comments: 'postId' },
  albums: { photos: 'albumId' },
};

async function handleGET(req, res, route, query) {
  const { table, id, sub } = route;

  if (id !== null && sub) {
    const parentExists = db.getOne(table, id);
    if (!parentExists) return notFound(res);

    const fkMap = NESTED[table] || {};
    if (!fkMap[sub]) return notFound(res, `No nested route '${sub}' under '${table}'`);

    const results = db.listAll(sub, { [fkMap[sub]]: String(id), ...query });
    return json(res, 200, results);
  }

  if (id !== null) {
    const row = db.getOne(table, id);
    return row ? json(res, 200, row) : notFound(res);
  }

  const rows = db.listAll(table, query);
  json(res, 200, rows);
}

async function handlePOST(req, res, route) {
  const { table } = route;
  let body;
  try { body = await readBody(req, res); }
  catch (e) { if (e !== BODY_TOO_LARGE) return badRequest(res, 'Invalid JSON body'); return; }

  if (!body.id) body.id = db.nextId(table);

  try {
    const created = db.insertOne(table, body);
    json(res, 201, created);
  } catch (e) {
    badRequest(res, e.message);
  }
}

async function handlePUT(req, res, route) {
  const { table, id } = route;
  if (id === null) return badRequest(res, 'PUT requires an id');

  let body;
  try { body = await readBody(req, res); }
  catch (e) { if (e !== BODY_TOO_LARGE) return badRequest(res, 'Invalid JSON body'); return; }

  const updated = db.updateOne(table, id, body, true);
  updated ? json(res, 200, updated) : notFound(res);
}

async function handlePATCH(req, res, route) {
  const { table, id } = route;
  if (id === null) return badRequest(res, 'PATCH requires an id');

  let body;
  try { body = await readBody(req, res); }
  catch (e) { if (e !== BODY_TOO_LARGE) return badRequest(res, 'Invalid JSON body'); return; }

  const updated = db.updateOne(table, id, body, false);
  updated ? json(res, 200, updated) : notFound(res);
}

function handleDELETE(_req, res, route) {
  const { table, id } = route;
  if (id === null) return badRequest(res, 'DELETE requires an id');

  const deleted = db.deleteOne(table, id);
  deleted ? json(res, 200, {}) : notFound(res);
}

function handleHealth(res) {
  json(res, 200, {
    status: 'ok',
    redis: redis.connected ? 'connected' : 'disconnected',
    tables: db.TABLES,
    rateLimit: {
      enabled: rateLimitEnabled,
      max: rateLimitMax,
      windowMs: rateLimitWindowMs,
    },
  });
}

async function requestHandler(req, res) {
  const parsed = new URL(req.url, 'http://localhost');
  const pathname = parsed.pathname;
  const query = Object.fromEntries(parsed.searchParams);
  const method = req.method.toUpperCase();

  if (method === 'OPTIONS') {
    res.writeHead(204, {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    });
    return res.end();
  }

  if (pathname === '/health' || pathname === '/api/health') {
    return handleHealth(res);
  }

  if (pathname === '/' || pathname === '/api') {
    return json(res, 200, {
      message: 'json-api-server β€” JSONPlaceholder-compatible REST API',
      version: '1.0.0',
      endpoints: db.TABLES.map((t) => `/api/${t}`),
      docs: 'GET /health for server status',
    });
  }

  await new Promise((resolve) => {
    rateLimiter(req, res, resolve);
  });
  if (res.writableEnded) return;

  const route = parseRoute(pathname);
  if (!route) return notFound(res, `Unknown route: ${pathname}`);

  try {
    switch (method) {
      case 'GET': return await handleGET(req, res, route, query);
      case 'POST': return await handlePOST(req, res, route);
      case 'PUT': return await handlePUT(req, res, route);
      case 'PATCH': return await handlePATCH(req, res, route);
      case 'DELETE': return handleDELETE(req, res, route);
      default:
        return json(res, 405, { error: `Method ${method} not allowed` });
    }
  } catch (err) {
    console.error('[Error]', err);
    json(res, 500, { error: 'Internal Server Error', message: err.message });
  }
}

const server = http.createServer(requestHandler);

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') { // for testing
    server.listen(port, printLog);
  }
}

process.on('SIGINT', () => { server.close(); redis.quit().catch(() => { }); process.exit(0); });
process.on('SIGTERM', () => { server.close(); redis.quit().catch(() => { }); process.exit(0); });

module.exports = { server, requestHandler };