dangkhoa2016 commited on
Commit
1a25764
·
0 Parent(s):

feat: scaffold HTTP REST API server with SQLite backend

Browse files

- Set up the project with Node.js built-ins only (http, SQLite, Redis client)
- Implement JSONPlaceholder-compatible CRUD endpoints for all six resources
- Add in-memory and Redis-backed rate limiting
- Add dotenv-based environment loading with example env files

.env.example ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # json-api-server configuration
2
+ # ────────────────────────────────────────────────────────────────────────────────
3
+ # Env files live at project root (loaded by bin/start.js via dotenv).
4
+ #
5
+ # Loading order (lowest → highest priority):
6
+ # 1. .env.{NODE_ENV} — environment-specific overrides
7
+ # 2. .env — base defaults
8
+ # 3. System env vars — highest priority (e.g. PORT=5000 node bin/start.js)
9
+ #
10
+ # NODE_ENV mapping:
11
+ # development → .env.dev or .env.development
12
+ # test → .env.test
13
+ # production → .env.prod or .env.production
14
+
15
+ # Server
16
+ PORT=3000
17
+
18
+ # SQLite database path (relative to project root)
19
+ DB_PATH=./storage/data.db
20
+
21
+ # Redis (optional — rate limiting falls back to in-memory if unavailable)
22
+ # Option A: connection URL (takes priority over individual settings below)
23
+ # Useful for cloud providers (Upstash, Redis Cloud, etc.)
24
+ # REDIS_URL=redis://user:password@host:6379/0
25
+
26
+ # Option B: individual settings
27
+ REDIS_HOST=127.0.0.1
28
+ REDIS_PORT=6379
29
+ REDIS_DB=0
30
+ # REDIS_PASSWORD=your-password
31
+
32
+ # Rate limiting
33
+ RATE_LIMIT_ENABLED=true
34
+ RATE_LIMIT_MAX=100
35
+ RATE_LIMIT_WINDOW_MS=60000
.env.prod.example ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ─── Production configuration ───────────────────────────────────────────────────
2
+ # Loaded when NODE_ENV=production
3
+ # Uncomment and fill in your production values:
4
+ # PORT=8080
5
+ # DB_PATH=./storage/prod.db
6
+
7
+ # REDIS_URL=redis://user:password@your-cloud-redis:6379/0
8
+ # REDIS_HOST=127.0.0.1
9
+ # REDIS_PORT=6379
10
+ # REDIS_DB=0
11
+ # REDIS_PASSWORD=
12
+
13
+ # Rate limiting
14
+ # RATE_LIMIT_ENABLED=true
15
+ # RATE_LIMIT_MAX=1000
16
+ # RATE_LIMIT_WINDOW_MS=60000
.env.test ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ─── Test configuration ─────────────────────────────────────────────────────────
2
+ # Loaded when NODE_ENV=test
3
+ PORT=3001
4
+ DB_PATH=./storage/test.db
5
+
6
+ # Redis (optional — rate limiting falls back to in-memory if unavailable)
7
+ # REDIS_URL=
8
+ # REDIS_HOST=127.0.0.1
9
+ # REDIS_PORT=6379
10
+ # REDIS_DB=0
11
+ # REDIS_PASSWORD=
12
+
13
+ # Rate limiting
14
+ RATE_LIMIT_ENABLED=true
15
+ # RATE_LIMIT_MAX=100
16
+ # RATE_LIMIT_WINDOW_MS=60000
.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ src/public/favicon.ico filter=lfs diff=lfs merge=lfs -text
2
+ src/public/favicon.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ temp
2
+ .env
3
+ .env.prod
4
+ .env.production
5
+ node_modules
6
+ coverage
7
+ storage/*
8
+ !storage/.gitkeep
9
+
10
+ .env.dev
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dang Khoa <i.am@dangkhoa.dev>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # json-api-server
2
+
3
+ A JSONPlaceholder-compatible REST API built with **Node.js built-ins only** — zero runtime dependencies. Uses `node:sqlite` for storage and a custom Redis client implemented over the raw RESP protocol via TCP sockets.
4
+
5
+ ## Requirements
6
+
7
+ - **Node.js >= 22** (uses built-in `node:sqlite`)
8
+ - **Redis** (optional — rate limiting falls back to in-memory if unavailable)
9
+
10
+ ## Quick Start
11
+
12
+ ```bash
13
+ git clone <repo-url>
14
+ cd json-api-server
15
+
16
+ npm start
17
+ # or with file watching for development:
18
+ npm run dev
19
+ ```
20
+
21
+ > **Note:** Node 22 may show a warning that `node:sqlite` is experimental. This is harmless.
22
+
23
+ ---
24
+
25
+ ## Configuration
26
+
27
+ Environment files are loaded by `src/load-env.js` (auto-run via `src/config.js`). All existing files in the chain are loaded with `override: false` — `process.env` values and earlier files take precedence over later ones. System env vars always take highest priority (e.g. `PORT=5000 npm start`).
28
+
29
+ `NODE_ENV` defaults to `development` if not set. In **production**, `dotenv` is **completely skipped** — set environment variables through your deployment environment instead (systemd, Docker, Kubernetes, etc.).
30
+
31
+ | NODE_ENV | dotenv | Fallback chain (tried in order) |
32
+ |---------------------|--------|----------------------------------|
33
+ | `development` | ✅ | `.env` ← `.env.dev` ← `.env.development` |
34
+ | `production-local` | ✅ | `.env.prod` ← `.env.production` |
35
+ | `test` | ✅ | `.env.test` |
36
+ | `production` | ❌ skipped | _(use system env vars)_ |
37
+
38
+ ### Variables
39
+
40
+ | Variable | Default | Description |
41
+ |------------------------|-------------|----------------------------------------|
42
+ | `PORT` | `3000` | Server port |
43
+ | `DB_PATH` | `./storage/data.db` | SQLite database file path |
44
+ | `REDIS_URL` | _(none)_ | Redis connection URL (takes priority). Format: `redis://user:password@host:port/db` |
45
+ | `REDIS_HOST` | `127.0.0.1` | Redis host |
46
+ | `REDIS_PORT` | `6379` | Redis port |
47
+ | `REDIS_DB` | `0` | Redis database index |
48
+ | `REDIS_PASSWORD` | _(none)_ | Redis password (for `AUTH`) |
49
+ | `RATE_LIMIT_ENABLED` | `true` | Enable/disable rate limiting |
50
+ | `RATE_LIMIT_MAX` | `100` | Max requests per time window |
51
+ | `RATE_LIMIT_WINDOW_MS` | `60000` | Time window in milliseconds (default 1 min) |
52
+
53
+ ---
54
+
55
+ ## API Endpoints
56
+
57
+ ### Resources
58
+
59
+ | Method | Path | Description |
60
+ |----------|-----------------------------|------------------------------|
61
+ | `GET` | `/api/users` | List all users |
62
+ | `GET` | `/api/users/:id` | Get user by ID |
63
+ | `GET` | `/api/users/:id/posts` | Posts by user |
64
+ | `GET` | `/api/users/:id/albums` | Albums by user |
65
+ | `GET` | `/api/users/:id/todos` | Todos by user |
66
+ | `GET` | `/api/posts` | List all posts |
67
+ | `GET` | `/api/posts/:id` | Get post by ID |
68
+ | `GET` | `/api/posts/:id/comments` | Comments on post |
69
+ | `GET` | `/api/comments` | List all comments |
70
+ | `GET` | `/api/albums` | List all albums |
71
+ | `GET` | `/api/albums/:id/photos` | Photos in album |
72
+ | `GET` | `/api/photos` | List all photos |
73
+ | `GET` | `/api/todos` | List all todos |
74
+ | `POST` | `/api/:table` | Create a new resource |
75
+ | `PUT` | `/api/:table/:id` | Replace resource entirely |
76
+ | `PATCH` | `/api/:table/:id` | Partial update |
77
+ | `DELETE` | `/api/:table/:id` | Delete resource |
78
+
79
+ ### Query String Filtering
80
+
81
+ ```bash
82
+ # Filter posts by userId
83
+ GET /api/posts?userId=1
84
+
85
+ # Filter todos by userId and completed status
86
+ GET /api/todos?userId=1&completed=false
87
+
88
+ # Filter comments by postId
89
+ GET /api/comments?postId=1
90
+ ```
91
+
92
+ Filterable columns vary by table (e.g., `title`, `email`, `username`). The `completed` field accepts `true`/`false` strings.
93
+
94
+ ### System Endpoints
95
+
96
+ | Path | Description |
97
+ |-------------------|--------------------------------------|
98
+ | `GET /` | API info with available endpoints |
99
+ | `GET /api` | API info (same as above) |
100
+ | `GET /health` | Server status (Redis, tables, rate limit config) |
101
+ | `GET /api/health` | Same as above |
102
+
103
+ ---
104
+
105
+ ## Response Headers
106
+
107
+ Every response includes CORS and rate-limit headers:
108
+
109
+ ```
110
+ Access-Control-Allow-Origin: *
111
+ X-Powered-By: json-api-server/1.0
112
+ X-RateLimit-Limit: 100
113
+ X-RateLimit-Remaining: 99
114
+ X-RateLimit-Reset: 58 ← seconds until window resets
115
+ X-RateLimit-Store: redis ← "redis" or "memory"
116
+ ```
117
+
118
+ When the rate limit is exceeded, a `429 Too Many Requests` response is returned:
119
+
120
+ ```json
121
+ {
122
+ "error": "Too Many Requests",
123
+ "message": "Rate limit exceeded. Max 100 requests per 60s window.",
124
+ "retryAfter": 45
125
+ }
126
+ ```
127
+
128
+ ---
129
+
130
+ ## Examples
131
+
132
+ ```bash
133
+ # List users
134
+ curl http://localhost:3000/api/users
135
+
136
+ # Create a new post
137
+ curl -X POST http://localhost:3000/api/posts \
138
+ -H "Content-Type: application/json" \
139
+ -d '{"userId": 1, "title": "Hello", "body": "World"}'
140
+
141
+ # Partial update
142
+ curl -X PATCH http://localhost:3000/api/posts/1 \
143
+ -H "Content-Type: application/json" \
144
+ -d '{"title": "Updated title"}'
145
+
146
+ # Delete
147
+ curl -X DELETE http://localhost:3000/api/posts/1
148
+
149
+ # Health check
150
+ curl http://localhost:3000/health
151
+ ```
152
+
153
+ ---
154
+
155
+ ## Architecture
156
+
157
+ ```
158
+ json-api-server/
159
+ ├── bin/
160
+ │ └── start.js # Entry point — loads .env via src/load-env.js, starts server
161
+ ├── src/
162
+ │ ├── config.js # Centralized config — auto-loads dotenv via load-env.js, exports camelCase
163
+ │ ├── load-env.js # Shared dotenv loader (auto-run on require, skips in production)
164
+ │ ├── server.js # HTTP server, routing, middleware, handlers
165
+ │ ├── database.js # SQLite layer (node:sqlite) — migration, seed, CRUD (reads config.js)
166
+ │ ├── rate-limiter.js # Rate limiter (Redis or in-memory fallback)
167
+ │ └── redis.js # Pure-Node Redis client via RESP protocol over TCP
168
+ ├── tests/
169
+ │ └── test.js # Integration tests
170
+ ├── manual/
171
+ │ ├── curl.sh # Quick curl commands
172
+ │ └── inspect-queries.sql # SQL queries for database inspection
173
+ ├── storage/ # SQLite database files (auto-created)
174
+ ├── temp/ # Temporary files (gitignored)
175
+ ├── .env # Base configuration (loaded last — lowest priority)
176
+ ├── .env.dev # Development overrides
177
+ ├── .env.test # Test configuration (port 3001, separate DB, no rate limit)
178
+ ├── .env.prod.example # Production template (copy to .env.prod)
179
+ ├── .env.example # Reference for all available variables
180
+ ├── package.json # Metadata and scripts
181
+ ├── LICENSE # MIT license
182
+ ├── README.md # Documentation
183
+ └── .gitignore # Git ignore rules
184
+ ```
185
+
186
+ ### Startup Flow
187
+
188
+ ```
189
+ bin/start.js → src/load-env.js (loads .env per NODE_ENV, skipped in production)
190
+ → src/server.js
191
+ ├── src/config.js (centralized config, auto-loads dotenv)
192
+ ├── src/database.js (SQLite schema + seed)
193
+ ├── src/redis.js (pure RESP + AUTH + URL)
194
+ └── src/rate-limiter.js (Redis || in-memory)
195
+ ```
196
+
197
+ ### Request Flow
198
+
199
+ ```
200
+ HTTP Request → CORS headers → Rate limiter → Route parser → Handler → JSON Response
201
+ ```
202
+
203
+ ---
204
+
205
+ ## Database
206
+
207
+ - **6 tables:** `users`, `posts`, `comments`, `albums`, `photos`, `todos`
208
+ - **WAL mode** for better concurrent read performance
209
+ - **Foreign keys** enforced via `PRAGMA foreign_keys=ON`
210
+ - **Seed data** auto-generated on first run:
211
+ - 5 users (with `address` and `company` stored as JSON, parsed on read)
212
+ - 50 posts (10 per user)
213
+ - 250 comments (5 per post)
214
+ - 10 albums (2 per user)
215
+ - 50 photos (5 per album)
216
+ - 20 todos (4 per user, `completed` stored as 0/1 integer, returned as boolean)
217
+
218
+ ### Helper Script
219
+
220
+ ```bash
221
+ sqlite3 storage/data.db < manual/inspect-queries.sql
222
+ ```
223
+
224
+ This runs comprehensive queries to inspect row counts, column metadata, relationships, integrity checks, and statistics.
225
+
226
+ ---
227
+
228
+ ## Testing
229
+
230
+ ```bash
231
+ # Start server in test mode (uses .env.test: port 3001, separate DB, no rate limit)
232
+ NODE_ENV=test npm start &
233
+
234
+ # Run tests (they connect to localhost:3000 by default)
235
+ npm test
236
+ # or
237
+ node tests/test.js
238
+ ```
239
+
240
+ The integration test automatically verifies all endpoints, including CRUD operations, nested routes, filtering, rate-limit headers, and 404 handling.
241
+
242
+ ---
243
+
244
+ ## Implementation Notes
245
+
246
+ - **Zero runtime dependencies** — only Node.js built-in modules (`http`, `url`, `fs`, `path`, `net`, `node:sqlite`). `dotenv` is a dev dependency.
247
+ - **Pure RESP protocol** — the Redis client in `src/redis.js` implements the Redis serialization protocol over raw TCP sockets without any third-party library. Supports `AUTH` password authentication and `REDIS_URL` connection strings.
248
+ - **Centralized config** — all environment variables are read in `src/config.js` and exported as camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, etc.) for use across the codebase.
249
+ - **Shared env loader** — `src/load-env.js` is auto-run on require by `src/config.js`. It loads environment-specific `.env` files based on `NODE_ENV` using a priority chain (development tries `.env` → `.env.dev` → `.env.development`). In production, dotenv is skipped entirely — env vars must come from the deployment environment. Both `bin/start.js` and any script requiring `config.js` get correct env values automatically.
250
+ - **CORS** enabled on all routes
251
+ - **Graceful shutdown** — handles `SIGINT` and `SIGTERM` to close the server and Redis connection cleanly
252
+
253
+ ## License
254
+
255
+ [MIT](LICENSE) — Copyright (c) 2026 Dang Khoa &lt;i.am@dangkhoa.dev&gt;
bin/start.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // dotenv loaded automatically by src/config.js
5
+ const ENV = (process.env.NODE_ENV || 'development').toLowerCase();
6
+
7
+ console.log(`[Start] NODE_ENV=${ENV}`);
8
+ require('../src/server');
manual/curl.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ curl localhost:3000/api/users | jq length
2
+ curl localhost:3000/api/posts | jq length
3
+ curl localhost:3000/api/comments | jq length
4
+ curl localhost:3000/api/photos | jq length
5
+ curl localhost:3000/api/todos | jq length
manual/inspect-queries.sql ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- ==============================================================================
2
+ -- Database Inspection — json-api-server
3
+ -- Usage: sqlite3 storage/data.db < manual/inspect-queries.sql
4
+ -- ==============================================================================
5
+
6
+ -- 1. OVERVIEW
7
+ -- ..............................................................................
8
+ SELECT 'users' AS table_name, COUNT(*) AS row_count FROM users
9
+ UNION ALL SELECT 'posts', COUNT(*) FROM posts
10
+ UNION ALL SELECT 'comments', COUNT(*) FROM comments
11
+ UNION ALL SELECT 'albums', COUNT(*) FROM albums
12
+ UNION ALL SELECT 'photos', COUNT(*) FROM photos
13
+ UNION ALL SELECT 'todos', COUNT(*) FROM todos
14
+ ORDER BY row_count DESC;
15
+
16
+ SELECT m.name AS table_name, COUNT(*) AS column_count
17
+ FROM sqlite_master m
18
+ JOIN pragma_table_info(m.name) ON 1=1
19
+ WHERE m.type = 'table'
20
+ GROUP BY m.name
21
+ ORDER BY m.name;
22
+
23
+ -- 2. USERS
24
+ -- ..............................................................................
25
+ SELECT id, name, username, email, phone FROM users ORDER BY id;
26
+
27
+ SELECT id, name,
28
+ substr(address, 1, 50) AS address_preview,
29
+ substr(company, 1, 50) AS company_preview
30
+ FROM users ORDER BY id;
31
+
32
+ -- 3. POSTS
33
+ -- ..............................................................................
34
+ SELECT p.id, p.userId, u.name AS author, substr(p.title, 1, 50) AS title
35
+ FROM posts p
36
+ JOIN users u ON u.id = p.userId
37
+ ORDER BY p.id;
38
+
39
+ SELECT u.id, u.name, COUNT(p.id) AS post_count
40
+ FROM users u
41
+ LEFT JOIN posts p ON p.userId = u.id
42
+ GROUP BY u.id
43
+ ORDER BY post_count DESC;
44
+
45
+ -- 4. COMMENTS
46
+ -- ..............................................................................
47
+ SELECT c.id, c.postId, c.name, c.email, substr(c.body, 1, 40) AS body_preview
48
+ FROM comments c
49
+ ORDER BY c.id
50
+ LIMIT 10;
51
+
52
+ SELECT postId, COUNT(*) AS comment_count
53
+ FROM comments
54
+ GROUP BY postId
55
+ ORDER BY postId;
56
+
57
+ -- 5. ALBUMS & PHOTOS
58
+ -- ..............................................................................
59
+ SELECT a.id, a.userId, u.name AS owner, a.title
60
+ FROM albums a
61
+ JOIN users u ON u.id = a.userId
62
+ ORDER BY a.id;
63
+
64
+ SELECT a.id, a.title, COUNT(p.id) AS photo_count
65
+ FROM albums a
66
+ LEFT JOIN photos p ON p.albumId = a.id
67
+ GROUP BY a.id
68
+ ORDER BY a.id;
69
+
70
+ SELECT id, albumId, substr(title, 1, 40) AS title, url
71
+ FROM photos
72
+ ORDER BY id
73
+ LIMIT 10;
74
+
75
+ -- 6. TODOS
76
+ -- ..............................................................................
77
+ SELECT t.id, t.userId, u.name AS user, substr(t.title, 1, 40) AS title, t.completed
78
+ FROM todos t
79
+ JOIN users u ON u.id = t.userId
80
+ ORDER BY t.id;
81
+
82
+ SELECT u.name,
83
+ COUNT(t.id) AS total,
84
+ SUM(CASE WHEN t.completed THEN 1 ELSE 0 END) AS done,
85
+ SUM(CASE WHEN NOT t.completed THEN 1 ELSE 0 END) AS pending
86
+ FROM users u
87
+ LEFT JOIN todos t ON t.userId = u.id
88
+ GROUP BY u.id
89
+ ORDER BY u.id;
90
+
91
+ -- 7. RELATIONSHIPS & INTEGRITY
92
+ -- ..............................................................................
93
+ SELECT u.id, u.name,
94
+ COUNT(DISTINCT p.id) AS posts,
95
+ COUNT(DISTINCT c.id) AS comments_on_posts,
96
+ COUNT(DISTINCT a.id) AS albums,
97
+ COUNT(DISTINCT t.id) AS todos
98
+ FROM users u
99
+ LEFT JOIN posts p ON p.userId = u.id
100
+ LEFT JOIN comments c ON c.postId IN (SELECT id FROM posts WHERE userId = u.id)
101
+ LEFT JOIN albums a ON a.userId = u.id
102
+ LEFT JOIN todos t ON t.userId = u.id
103
+ GROUP BY u.id
104
+ ORDER BY u.id;
105
+
106
+ SELECT 'posts' AS tbl, 'userId' AS col, p.userId AS val
107
+ FROM posts p LEFT JOIN users u ON u.id = p.userId WHERE u.id IS NULL
108
+ UNION ALL
109
+ SELECT 'comments', 'postId', c.postId
110
+ FROM comments c LEFT JOIN posts p ON p.id = c.postId WHERE p.id IS NULL
111
+ UNION ALL
112
+ SELECT 'albums', 'userId', a.userId
113
+ FROM albums a LEFT JOIN users u ON u.id = a.userId WHERE u.id IS NULL;
114
+
115
+ -- 8. STATISTICS
116
+ -- ..............................................................................
117
+ SELECT 'posts' AS type, AVG(LENGTH(body)) AS avg_len, MIN(LENGTH(body)) AS min_len, MAX(LENGTH(body)) AS max_len FROM posts
118
+ UNION ALL
119
+ SELECT 'comments', AVG(LENGTH(body)), MIN(LENGTH(body)), MAX(LENGTH(body)) FROM comments;
120
+
121
+ SELECT CASE WHEN completed THEN 'done' ELSE 'pending' END AS status,
122
+ COUNT(*) AS count,
123
+ ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM todos), 1) AS pct
124
+ FROM todos GROUP BY completed;
125
+
126
+ SELECT 'user_activity' AS metric, MAX(pc) || ' posts' AS value FROM (SELECT userId, COUNT(*) AS pc FROM posts GROUP BY userId)
127
+ UNION ALL
128
+ SELECT 'user_activity', MAX(ac) || ' albums' FROM (SELECT userId, COUNT(*) AS ac FROM albums GROUP BY userId)
129
+ UNION ALL
130
+ SELECT 'user_activity', MAX(tc) || ' todos' FROM (SELECT userId, COUNT(*) AS tc FROM todos GROUP BY userId);
package.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "json-api-server",
3
+ "version": "1.0.0",
4
+ "description": "JSONPlaceholder-compatible REST API — Node.js built-ins only, SQLite + Redis",
5
+ "main": "bin/start.js",
6
+ "author": {
7
+ "email": "i.am@dangkhoa.dev",
8
+ "name": "Dang Khoa",
9
+ "url": "https://dangkhoa.dev"
10
+ },
11
+ "scripts": {
12
+ "start": "node bin/start.js",
13
+ "prod": "NODE_ENV=production-local node bin/start.js",
14
+ "dev": "node --watch bin/start.js",
15
+ "test": "node tests/test.js"
16
+ },
17
+ "engines": {
18
+ "node": ">=22.0.0"
19
+ },
20
+ "keywords": [
21
+ "rest",
22
+ "api",
23
+ "sqlite",
24
+ "redis",
25
+ "jsonplaceholder"
26
+ ],
27
+ "license": "MIT",
28
+ "devDependencies": {
29
+ "dotenv": "^17.4.2"
30
+ }
31
+ }
src/config.js ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+
5
+ require('./load-env');
6
+
7
+ const PORT = parseInt(process.env.PORT || '3000', 10);
8
+
9
+ const DB_PATH = process.env.DB_PATH || path.join(__dirname, '..', 'storage', 'data.db');
10
+
11
+ const REDIS_URL = process.env.REDIS_URL || null;
12
+ const REDIS_HOST = process.env.REDIS_HOST || '127.0.0.1';
13
+ const REDIS_PORT = parseInt(process.env.REDIS_PORT || '6379', 10);
14
+ const REDIS_DB = parseInt(process.env.REDIS_DB || '0', 10);
15
+ const REDIS_PASSWORD = process.env.REDIS_PASSWORD;
16
+
17
+ const redisOpts = REDIS_URL
18
+ ? { url: REDIS_URL }
19
+ : { host: REDIS_HOST, port: REDIS_PORT, db: REDIS_DB, password: REDIS_PASSWORD };
20
+
21
+ const RATE_LIMIT_ENABLED_STR = process.env.RATE_LIMIT_ENABLED || 'true';
22
+ const RATE_LIMIT_ENABLED = RATE_LIMIT_ENABLED_STR !== 'false';
23
+ const RATE_LIMIT_MAX = parseInt(process.env.RATE_LIMIT_MAX || '100', 10);
24
+ const RATE_LIMIT_WINDOW_MS = parseInt(process.env.RATE_LIMIT_WINDOW_MS || '60000', 10);
25
+ const RATE_LIMIT_WINDOW_SEC = Math.ceil(RATE_LIMIT_WINDOW_MS / 1000);
26
+
27
+ module.exports = {
28
+ port: PORT,
29
+ dbPath: DB_PATH,
30
+ redisOpts,
31
+ rateLimitEnabled: RATE_LIMIT_ENABLED,
32
+ rateLimitMax: RATE_LIMIT_MAX,
33
+ rateLimitWindowMs: RATE_LIMIT_WINDOW_MS,
34
+ rateLimitWindowSec: RATE_LIMIT_WINDOW_SEC,
35
+ };
src/database.js ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const { DatabaseSync } = require('node:sqlite');
4
+ const { dbPath } = require('./config');
5
+
6
+ let db;
7
+
8
+ function getDb() {
9
+ if (!db) {
10
+ db = new DatabaseSync(dbPath);
11
+ db.exec('PRAGMA journal_mode=WAL');
12
+ db.exec('PRAGMA foreign_keys=ON');
13
+ }
14
+ return db;
15
+ }
16
+
17
+ function migrate() {
18
+ const d = getDb();
19
+ d.exec(`
20
+ CREATE TABLE IF NOT EXISTS users (
21
+ id INTEGER PRIMARY KEY,
22
+ name TEXT,
23
+ username TEXT UNIQUE,
24
+ email TEXT,
25
+ phone TEXT,
26
+ website TEXT,
27
+ address TEXT,
28
+ company TEXT
29
+ );
30
+
31
+ CREATE TABLE IF NOT EXISTS posts (
32
+ id INTEGER PRIMARY KEY,
33
+ userId INTEGER,
34
+ title TEXT,
35
+ body TEXT,
36
+ FOREIGN KEY(userId) REFERENCES users(id)
37
+ );
38
+
39
+ CREATE TABLE IF NOT EXISTS comments (
40
+ id INTEGER PRIMARY KEY,
41
+ postId INTEGER,
42
+ name TEXT,
43
+ email TEXT,
44
+ body TEXT,
45
+ FOREIGN KEY(postId) REFERENCES posts(id)
46
+ );
47
+
48
+ CREATE TABLE IF NOT EXISTS albums (
49
+ id INTEGER PRIMARY KEY,
50
+ userId INTEGER,
51
+ title TEXT,
52
+ FOREIGN KEY(userId) REFERENCES users(id)
53
+ );
54
+
55
+ CREATE TABLE IF NOT EXISTS photos (
56
+ id INTEGER PRIMARY KEY,
57
+ albumId INTEGER,
58
+ title TEXT,
59
+ url TEXT,
60
+ thumbnailUrl TEXT,
61
+ FOREIGN KEY(albumId) REFERENCES albums(id)
62
+ );
63
+
64
+ CREATE TABLE IF NOT EXISTS todos (
65
+ id INTEGER PRIMARY KEY,
66
+ userId INTEGER,
67
+ title TEXT,
68
+ completed INTEGER DEFAULT 0,
69
+ FOREIGN KEY(userId) REFERENCES users(id)
70
+ );
71
+ `);
72
+ }
73
+
74
+ function seed() {
75
+ const d = getDb();
76
+ const count = d.prepare('SELECT COUNT(*) as c FROM users').get();
77
+ if (count.c > 0) return;
78
+
79
+ console.log('[DB] Seeding initial data…');
80
+
81
+ const users = [
82
+ { id: 1, name: 'Leanne Graham', username: 'Bret', email: 'Sincere@april.biz', phone: '1-770-736-8031 x56442', website: 'hildegard.org', address: JSON.stringify({ street: 'Kulas Light', suite: 'Apt. 556', city: 'Gwenborough', zipcode: '92998-3874', geo: { lat: '-37.3159', lng: '81.1496' } }), company: JSON.stringify({ name: 'Romaguera-Crona', catchPhrase: 'Multi-layered client-server neural-net', bs: 'harness real-time e-markets' }) },
83
+ { id: 2, name: 'Ervin Howell', username: 'Antonette', email: 'Shanna@melissa.tv', phone: '010-692-6593 x09125', website: 'anastasia.net', address: JSON.stringify({ street: 'Victor Plains', suite: 'Suite 879', city: 'Wisokyburgh', zipcode: '90566-7771', geo: { lat: '-43.9509', lng: '-34.7618' } }), company: JSON.stringify({ name: 'Deckow-Crist', catchPhrase: 'Proactive didactic contingency', bs: 'synergize scalable supply-chains' }) },
84
+ { id: 3, name: 'Clementine Bauch', username: 'Samantha', email: 'Nathan@yesenia.net', phone: '1-463-123-4447', website: 'ramiro.info', address: JSON.stringify({ street: 'Douglas Extension', suite: 'Suite 847', city: 'McKenziehaven', zipcode: '59590-4157', geo: { lat: '-68.6102', lng: '-47.0653' } }), company: JSON.stringify({ name: 'Romaguera-Jacobson', catchPhrase: 'Face to face bifurcated interface', bs: 'e-enable strategic applications' }) },
85
+ { id: 4, name: 'Patricia Lebsack', username: 'Karianne', email: 'Julianne.OConner@kory.org', phone: '493-170-9623 x156', website: 'kale.biz', address: JSON.stringify({ street: 'Hoeger Mall', suite: 'Apt. 692', city: 'South Elvis', zipcode: '53919-4257', geo: { lat: '29.4572', lng: '-164.2990' } }), company: JSON.stringify({ name: 'Robel-Corkery', catchPhrase: 'Multi-tiered zero tolerance productivity', bs: 'transition cutting-edge web services' }) },
86
+ { id: 5, name: 'Chelsey Dietrich', username: 'Kamren', email: 'Lucio_Hettinger@annie.ca', phone: '(254)954-1289', website: 'demarco.info', address: JSON.stringify({ street: 'Skiles Walks', suite: 'Suite 351', city: 'Roscoeview', zipcode: '33263', geo: { lat: '-31.8129', lng: '62.5342' } }), company: JSON.stringify({ name: 'Keebler LLC', catchPhrase: 'User-centric fault-tolerant solution', bs: 'revolutionize end-to-end systems' }) },
87
+ ];
88
+
89
+ const insertUser = d.prepare(`INSERT INTO users (id,name,username,email,phone,website,address,company) VALUES (?,?,?,?,?,?,?,?)`);
90
+ for (const u of users) {
91
+ insertUser.run(u.id, u.name, u.username, u.email, u.phone, u.website, u.address, u.company);
92
+ }
93
+
94
+ const insertPost = d.prepare(`INSERT INTO posts (id,userId,title,body) VALUES (?,?,?,?)`);
95
+ const titles = ['sunt aut facere repellat provident', 'qui est esse', 'ea molestias quasi exercitationem', 'eum et est occaecati', 'nesciunt quas odio', 'dolorem eum magni eos aperiam', 'magnam facilis autem', 'dolorem dolore est ipsam', 'nesciunt iure omnis dolorem', 'optio molestias id quia eum'];
96
+ const bodies = ['quia et suscipit\nsuscipit recusandae consequuntur', 'est rerum tempore vitae\nsequi sint nihil reprehenderit dolor', 'et iusto sed quo iure\nvoluptatem occaecati omnis eligendi', 'ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda', 'repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem', 'ut aspernatur corporis harum nihil quis', 'eveniet quod temporibus', 'in ut explicabo rerum consectetur aut', 'eum accusamus quia doloribus', 'voluptas blanditiis repellat itaque'];
97
+ let postId = 1;
98
+ for (let u = 1; u <= 5; u++) {
99
+ for (let i = 0; i < 10; i++, postId++) {
100
+ insertPost.run(postId, u, titles[i], bodies[i]);
101
+ }
102
+ }
103
+
104
+ const insertComment = d.prepare(`INSERT INTO comments (id,postId,name,email,body) VALUES (?,?,?,?,?)`);
105
+ let commentId = 1;
106
+ for (let p = 1; p <= 50; p++) {
107
+ for (let i = 0; i < 5; i++, commentId++) {
108
+ insertComment.run(commentId, p, `Comment ${i + 1} on post ${p}`, `commenter${commentId}@example.com`, `Great post! Comment body ${commentId}.`);
109
+ }
110
+ }
111
+
112
+ const insertAlbum = d.prepare(`INSERT INTO albums (id,userId,title) VALUES (?,?,?)`);
113
+ const albumTitles = ['quidem molestiae enim', 'sunt qui excepturi placeat culpa', 'omnis laborum odio', 'non esse culpa molestiae omnis sed optio', 'eaque aut omnis a', 'natus impedit quibusdam illo est', 'quibusdam autem aliquid et et quia', 'cum voluptatibus rerum architecto harum nihil', 'quisquam choro et aut officiis'];
114
+ let albumId = 1;
115
+ for (let u = 1; u <= 5; u++) {
116
+ for (let i = 0; i < 2; i++, albumId++) {
117
+ insertAlbum.run(albumId, u, albumTitles[(albumId - 1) % albumTitles.length]);
118
+ }
119
+ }
120
+
121
+ const insertPhoto = d.prepare(`INSERT INTO photos (id,albumId,title,url,thumbnailUrl) VALUES (?,?,?,?,?)`);
122
+ let photoId = 1;
123
+ for (let a = 1; a <= 10; a++) {
124
+ for (let i = 0; i < 5; i++, photoId++) {
125
+ insertPhoto.run(photoId, a, `Photo ${photoId}`, `https://via.placeholder.com/600/${photoId}`, `https://via.placeholder.com/150/${photoId}`);
126
+ }
127
+ }
128
+
129
+ const insertTodo = d.prepare(`INSERT INTO todos (id,userId,title,completed) VALUES (?,?,?,?)`);
130
+ const todoTitles = ['delectus aut autem', 'quis ut nam facilis et officia qui', 'fugiat veniam minus', 'et porro tempora'];
131
+ let todoId = 1;
132
+ for (let u = 1; u <= 5; u++) {
133
+ for (let i = 0; i < 4; i++, todoId++) {
134
+ insertTodo.run(todoId, u, todoTitles[i], todoId % 2 === 0 ? 1 : 0);
135
+ }
136
+ }
137
+
138
+ console.log('[DB] Seeding done.');
139
+ }
140
+
141
+ function parseRow(table, row) {
142
+ if (!row) return null;
143
+ const r = { ...row };
144
+ if ('address' in r && typeof r.address === 'string') {
145
+ try { r.address = JSON.parse(r.address); } catch (_) { }
146
+ }
147
+ if ('company' in r && typeof r.company === 'string') {
148
+ try { r.company = JSON.parse(r.company); } catch (_) { }
149
+ }
150
+ if ('completed' in r) {
151
+ r.completed = Boolean(r.completed);
152
+ }
153
+ return r;
154
+ }
155
+
156
+ const TABLES = ['users', 'posts', 'comments', 'albums', 'photos', 'todos'];
157
+
158
+ const FILTER_COLS = {
159
+ users: ['id', 'name', 'username', 'email', 'phone', 'website'],
160
+ posts: ['id', 'userId', 'title'],
161
+ comments: ['id', 'postId', 'name', 'email'],
162
+ albums: ['id', 'userId', 'title'],
163
+ photos: ['id', 'albumId', 'title', 'url', 'thumbnailUrl'],
164
+ todos: ['id', 'userId', 'title', 'completed'],
165
+ };
166
+
167
+ function buildWhere(table, query) {
168
+ const cols = FILTER_COLS[table] || [];
169
+ const clauses = [];
170
+ const values = [];
171
+
172
+ for (const [k, v] of Object.entries(query)) {
173
+ if (cols.includes(k)) {
174
+ clauses.push(`${k} = ?`);
175
+ values.push(k === 'completed' ? (v === 'true' ? 1 : 0) : v);
176
+ }
177
+ }
178
+ return {
179
+ where: clauses.length ? ' WHERE ' + clauses.join(' AND ') : '',
180
+ values,
181
+ };
182
+ }
183
+
184
+ function listAll(table, query = {}) {
185
+ const d = getDb();
186
+ const { where, values } = buildWhere(table, query);
187
+ const rows = d.prepare(`SELECT * FROM ${table}${where}`).all(...values);
188
+ return rows.map((r) => parseRow(table, r));
189
+ }
190
+
191
+ function getOne(table, id) {
192
+ const d = getDb();
193
+ const row = d.prepare(`SELECT * FROM ${table} WHERE id = ?`).get(id);
194
+ return parseRow(table, row);
195
+ }
196
+
197
+ function insertOne(table, data) {
198
+ const d = getDb();
199
+ const cols = Object.keys(data);
200
+ const placeholders = cols.map(() => '?').join(',');
201
+ const vals = cols.map((c) => {
202
+ if (typeof data[c] === 'object' && data[c] !== null) return JSON.stringify(data[c]);
203
+ if (typeof data[c] === 'boolean') return data[c] ? 1 : 0;
204
+ return data[c];
205
+ });
206
+ const result = d.prepare(
207
+ `INSERT INTO ${table} (${cols.join(',')}) VALUES (${placeholders})`
208
+ ).run(...vals);
209
+ return getOne(table, result.lastInsertRowid);
210
+ }
211
+
212
+ function updateOne(table, id, data, replace = false) {
213
+ const d = getDb();
214
+ const existing = getOne(table, id);
215
+ if (!existing) return null;
216
+ const merged = replace ? { ...data, id } : { ...existing, ...data, id };
217
+ const cols = Object.keys(merged).filter((c) => c !== 'id');
218
+ const setClauses = cols.map((c) => `${c} = ?`).join(', ');
219
+ const vals = cols.map((c) => {
220
+ if (typeof merged[c] === 'object' && merged[c] !== null) return JSON.stringify(merged[c]);
221
+ if (typeof merged[c] === 'boolean') return merged[c] ? 1 : 0;
222
+ return merged[c] ?? null;
223
+ });
224
+ d.prepare(`UPDATE ${table} SET ${setClauses} WHERE id = ?`).run(...vals, id);
225
+ return getOne(table, id);
226
+ }
227
+
228
+ function deleteOne(table, id) {
229
+ const d = getDb();
230
+ const existing = getOne(table, id);
231
+ if (!existing) return null;
232
+ d.prepare(`DELETE FROM ${table} WHERE id = ?`).run(id);
233
+ return existing;
234
+ }
235
+
236
+ function nextId(table) {
237
+ const d = getDb();
238
+ const row = d.prepare(`SELECT MAX(id) as m FROM ${table}`).get();
239
+ return (row.m || 0) + 1;
240
+ }
241
+
242
+ module.exports = { migrate, seed, listAll, getOne, insertOne, updateOne, deleteOne, nextId, TABLES };
src/load-env.js ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+
5
+ function loadEnv() {
6
+ const env = (process.env.NODE_ENV || 'development').toLowerCase();
7
+
8
+ if (env === 'production') return;
9
+
10
+ const envFileMap = {
11
+ development: ['.env', '.env.dev', '.env.development'],
12
+ 'production-local': ['.env.prod', '.env.production'],
13
+ test: ['.env.test'],
14
+ };
15
+
16
+ const envFiles = envFileMap[env] || envFileMap.development;
17
+ const rootDir = path.join(__dirname, '..');
18
+
19
+ for (const file of envFiles) {
20
+ const fullPath = path.join(rootDir, file);
21
+ const { error } = require('dotenv').config({ path: fullPath, override: false });
22
+ if (error) {
23
+ if (error.code === 'ENOENT') continue;
24
+ console.error(`[dotenv] Error loading ${file}:`, error.message);
25
+ }
26
+ }
27
+ }
28
+
29
+ module.exports = { loadEnv };
src/rate-limiter.js ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const {
4
+ rateLimitWindowMs: WINDOW_MS,
5
+ rateLimitMax: MAX_REQ,
6
+ rateLimitEnabled: ENABLED,
7
+ rateLimitWindowSec: WINDOW_SEC,
8
+ } = require('./config');
9
+
10
+ const memStore = new Map();
11
+
12
+ function memFallback(ip) {
13
+ const now = Date.now();
14
+ let entry = memStore.get(ip);
15
+ if (!entry || entry.resetAt <= now) {
16
+ entry = { count: 0, resetAt: now + WINDOW_MS };
17
+ memStore.set(ip, entry);
18
+ }
19
+ entry.count++;
20
+ const remaining = Math.max(0, MAX_REQ - entry.count);
21
+ const reset = Math.ceil((entry.resetAt - now) / 1000);
22
+ return { count: entry.count, remaining, reset, limited: entry.count > MAX_REQ };
23
+ }
24
+
25
+ async function checkRedis(redis, ip) {
26
+ const key = `rl:${ip}`;
27
+ const count = await redis.incr(key);
28
+ if (count === 1) {
29
+ await redis.expire(key, WINDOW_SEC);
30
+ }
31
+ const ttl = await redis.ttl(key);
32
+ const remaining = Math.max(0, MAX_REQ - count);
33
+ return { count, remaining, reset: ttl, limited: count > MAX_REQ };
34
+ }
35
+
36
+ function createRateLimiter(redis) {
37
+ if (!ENABLED) {
38
+ return async (_req, _res, next) => next();
39
+ }
40
+
41
+ return async function rateLimiter(req, res, next) {
42
+ const ip =
43
+ (req.headers['x-forwarded-for'] || '').split(',')[0].trim() ||
44
+ req.socket.remoteAddress ||
45
+ 'unknown';
46
+
47
+ let info;
48
+ let usingRedis = false;
49
+
50
+ if (redis && redis.connected) {
51
+ try {
52
+ info = await checkRedis(redis, ip);
53
+ usingRedis = true;
54
+ } catch (_) {
55
+ info = memFallback(ip);
56
+ }
57
+ } else {
58
+ info = memFallback(ip);
59
+ }
60
+
61
+ res.setHeader('X-RateLimit-Limit', MAX_REQ);
62
+ res.setHeader('X-RateLimit-Remaining', info.remaining);
63
+ res.setHeader('X-RateLimit-Reset', info.reset);
64
+ res.setHeader('X-RateLimit-Store', usingRedis ? 'redis' : 'memory');
65
+
66
+ if (info.limited) {
67
+ res.writeHead(429, { 'Content-Type': 'application/json', 'Retry-After': WINDOW_SEC });
68
+ res.end(JSON.stringify({
69
+ error: 'Too Many Requests',
70
+ message: `Rate limit exceeded. Max ${MAX_REQ} requests per ${WINDOW_SEC}s window.`,
71
+ retryAfter: info.reset,
72
+ }));
73
+ return;
74
+ }
75
+
76
+ next();
77
+ };
78
+ }
79
+
80
+ module.exports = { createRateLimiter };
src/redis.js ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const net = require('net');
4
+
5
+ class RedisClient {
6
+ constructor({ url, host = '127.0.0.1', port = 6379, db = 0, password } = {}) {
7
+ if (url) {
8
+ const parsed = new URL(url);
9
+ host = parsed.hostname || host;
10
+ port = parsed.port ? parseInt(parsed.port, 10) : port;
11
+ if (parsed.password) password = parsed.password;
12
+ const dbMatch = parsed.pathname.match(/^\/(\d+)$/);
13
+ if (dbMatch) db = parseInt(dbMatch[1], 10);
14
+ }
15
+ this.host = host;
16
+ this.port = port;
17
+ this.db = db;
18
+ this.password = password;
19
+ this.socket = null;
20
+ this.connected = false;
21
+ this.queue = [];
22
+ this.buffer = '';
23
+ this._connecting = false;
24
+ }
25
+
26
+ _encode(...args) {
27
+ let cmd = `*${args.length}\r\n`;
28
+ for (const arg of args) {
29
+ const s = String(arg);
30
+ cmd += `$${Buffer.byteLength(s)}\r\n${s}\r\n`;
31
+ }
32
+ return cmd;
33
+ }
34
+
35
+ _parse(buf, offset = 0) {
36
+ if (offset >= buf.length) return null;
37
+ const type = buf[offset];
38
+
39
+ const lineEnd = buf.indexOf('\r\n', offset);
40
+ if (lineEnd === -1) return null;
41
+ const line = buf.slice(offset + 1, lineEnd);
42
+
43
+ switch (type) {
44
+ case 43: {
45
+ return { value: line, consumed: lineEnd + 2 };
46
+ }
47
+ case 45: {
48
+ const err = new Error(line);
49
+ return { value: err, consumed: lineEnd + 2, isError: true };
50
+ }
51
+ case 58: {
52
+ return { value: parseInt(line, 10), consumed: lineEnd + 2 };
53
+ }
54
+ case 36: {
55
+ const len = parseInt(line, 10);
56
+ if (len === -1) return { value: null, consumed: lineEnd + 2 };
57
+ const dataStart = lineEnd + 2;
58
+ const dataEnd = dataStart + len;
59
+ if (buf.length < dataEnd + 2) return null;
60
+ return { value: buf.slice(dataStart, dataEnd), consumed: dataEnd + 2 };
61
+ }
62
+ case 42: {
63
+ const count = parseInt(line, 10);
64
+ if (count === -1) return { value: null, consumed: lineEnd + 2 };
65
+ const arr = [];
66
+ let pos = lineEnd + 2;
67
+ for (let i = 0; i < count; i++) {
68
+ const item = this._parse(buf, pos);
69
+ if (!item) return null;
70
+ arr.push(item.value);
71
+ pos = item.consumed;
72
+ }
73
+ return { value: arr, consumed: pos };
74
+ }
75
+ default:
76
+ throw new Error(`Unknown RESP type: ${String.fromCharCode(type)}`);
77
+ }
78
+ }
79
+
80
+ _onData(data) {
81
+ this._rawBuf = this._rawBuf
82
+ ? Buffer.concat([this._rawBuf, data])
83
+ : Buffer.from(data);
84
+
85
+ let offset = 0;
86
+ while (this.queue.length > 0) {
87
+ const result = this._parse(this._rawBuf, offset);
88
+ if (!result) break;
89
+ offset = result.consumed;
90
+ const { resolve, reject } = this.queue.shift();
91
+ if (result.isError) {
92
+ reject(result.value);
93
+ } else {
94
+ resolve(result.value);
95
+ }
96
+ }
97
+ if (offset > 0) {
98
+ this._rawBuf = this._rawBuf.slice(offset);
99
+ }
100
+ }
101
+
102
+ connect() {
103
+ if (this.connected || this._connecting) return Promise.resolve();
104
+ this._connecting = true;
105
+
106
+ return new Promise((resolve, reject) => {
107
+ this.socket = net.createConnection({ host: this.host, port: this.port });
108
+ this._rawBuf = null;
109
+
110
+ this.socket.on('data', (d) => this._onData(d));
111
+ this.socket.on('error', (err) => {
112
+ this.connected = false;
113
+ this._connecting = false;
114
+ reject(err);
115
+ while (this.queue.length) {
116
+ this.queue.shift().reject(err);
117
+ }
118
+ });
119
+ this.socket.on('close', () => {
120
+ this.connected = false;
121
+ this._connecting = false;
122
+ });
123
+ this.socket.on('connect', async () => {
124
+ this.connected = true;
125
+ this._connecting = false;
126
+ try {
127
+ if (this.password) {
128
+ await this.send('AUTH', this.password);
129
+ }
130
+ if (this.db !== 0) {
131
+ await this.send('SELECT', this.db);
132
+ }
133
+ resolve();
134
+ } catch (err) {
135
+ this.connected = false;
136
+ reject(err);
137
+ }
138
+ });
139
+ });
140
+ }
141
+
142
+ send(...args) {
143
+ return new Promise((resolve, reject) => {
144
+ this.queue.push({ resolve, reject });
145
+ this.socket.write(this._encode(...args));
146
+ });
147
+ }
148
+
149
+ ping() { return this.send('PING'); }
150
+ auth(password) { return this.send('AUTH', password); }
151
+ get(key) { return this.send('GET', key); }
152
+ set(key, value, ...opts) { return this.send('SET', key, value, ...opts); }
153
+ setex(key, seconds, value) { return this.send('SETEX', key, seconds, value); }
154
+ incr(key) { return this.send('INCR', key); }
155
+ expire(key, seconds) { return this.send('EXPIRE', key, seconds); }
156
+ del(...keys) { return this.send('DEL', ...keys); }
157
+ ttl(key) { return this.send('TTL', key); }
158
+
159
+ quit() {
160
+ return this.send('QUIT').finally(() => this.socket.destroy());
161
+ }
162
+ }
163
+
164
+ module.exports = RedisClient;
src/server.js ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const http = require('http');
4
+
5
+ const { port, redisOpts, rateLimitMax, rateLimitEnabled,
6
+ rateLimitWindowMs, rateLimitWindowSec } = require('./config');
7
+ const RedisClient = require('./redis');
8
+ const { createRateLimiter } = require('./rate-limiter');
9
+ const db = require('./database');
10
+
11
+ db.migrate();
12
+ db.seed();
13
+
14
+ const redis = new RedisClient(redisOpts);
15
+
16
+ const rateLimiter = createRateLimiter(redis);
17
+
18
+ (async () => {
19
+ try {
20
+ await redis.connect();
21
+ await redis.ping();
22
+ console.log('[Redis] Connected ✓');
23
+ } catch (e) {
24
+ console.warn('[Redis] Unavailable — rate limiting falls back to in-memory:', e.message);
25
+ }
26
+ startServer();
27
+ })();
28
+
29
+ function json(res, status, data) {
30
+ const body = JSON.stringify(data, null, 2);
31
+ res.writeHead(status, {
32
+ 'Content-Type': 'application/json; charset=utf-8',
33
+ 'Access-Control-Allow-Origin': '*',
34
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
35
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
36
+ 'X-Powered-By': 'json-api-server/1.0',
37
+ });
38
+ res.end(body);
39
+ }
40
+
41
+ function notFound(res, msg = 'Not Found') {
42
+ json(res, 404, { error: msg });
43
+ }
44
+
45
+ function badRequest(res, msg = 'Bad Request') {
46
+ json(res, 400, { error: msg });
47
+ }
48
+
49
+ const MAX_BODY_SIZE = 1_048_576;
50
+ const BODY_TOO_LARGE = Symbol('BODY_TOO_LARGE');
51
+
52
+ function readBody(req, res) {
53
+ return new Promise((resolve, reject) => {
54
+ let body = '';
55
+ req.on('data', (chunk) => {
56
+ body += chunk;
57
+ if (body.length > MAX_BODY_SIZE) {
58
+ json(res, 413, { error: 'Request body too large', message: `Body exceeds ${MAX_BODY_SIZE} byte limit` });
59
+ req.destroy();
60
+ reject(BODY_TOO_LARGE);
61
+ }
62
+ });
63
+ req.on('end', () => {
64
+ try {
65
+ resolve(body ? JSON.parse(body) : {});
66
+ } catch (_) {
67
+ reject(new Error('Invalid JSON'));
68
+ }
69
+ });
70
+ req.on('error', reject);
71
+ });
72
+ }
73
+
74
+ function parseRoute(pathname) {
75
+ const parts = pathname.replace(/^\/+|\/+$/g, '').split('/');
76
+ if (parts[0] === 'api') parts.shift();
77
+
78
+ const [table, rawId, sub] = parts;
79
+ const id = rawId ? parseInt(rawId, 10) : null;
80
+
81
+ if (!db.TABLES.includes(table)) return null;
82
+ if (rawId && isNaN(id)) return null;
83
+
84
+ return { table, id, sub };
85
+ }
86
+
87
+ const NESTED = {
88
+ users: { posts: 'userId', albums: 'userId', todos: 'userId' },
89
+ posts: { comments: 'postId' },
90
+ albums: { photos: 'albumId' },
91
+ };
92
+
93
+ async function handleGET(req, res, route, query) {
94
+ const { table, id, sub } = route;
95
+
96
+ if (id !== null && sub) {
97
+ const parentExists = db.getOne(table, id);
98
+ if (!parentExists) return notFound(res);
99
+
100
+ const fkMap = NESTED[table] || {};
101
+ if (!fkMap[sub]) return notFound(res, `No nested route '${sub}' under '${table}'`);
102
+
103
+ const results = db.listAll(sub, { [fkMap[sub]]: String(id), ...query });
104
+ return json(res, 200, results);
105
+ }
106
+
107
+ if (id !== null) {
108
+ const row = db.getOne(table, id);
109
+ return row ? json(res, 200, row) : notFound(res);
110
+ }
111
+
112
+ const rows = db.listAll(table, query);
113
+ json(res, 200, rows);
114
+ }
115
+
116
+ async function handlePOST(req, res, route) {
117
+ const { table } = route;
118
+ let body;
119
+ try { body = await readBody(req, res); }
120
+ catch (e) { if (e !== BODY_TOO_LARGE) return badRequest(res, 'Invalid JSON body'); return; }
121
+
122
+ if (!body.id) body.id = db.nextId(table);
123
+
124
+ try {
125
+ const created = db.insertOne(table, body);
126
+ json(res, 201, created);
127
+ } catch (e) {
128
+ badRequest(res, e.message);
129
+ }
130
+ }
131
+
132
+ async function handlePUT(req, res, route) {
133
+ const { table, id } = route;
134
+ if (id === null) return badRequest(res, 'PUT requires an id');
135
+
136
+ let body;
137
+ try { body = await readBody(req, res); }
138
+ catch (e) { if (e !== BODY_TOO_LARGE) return badRequest(res, 'Invalid JSON body'); return; }
139
+
140
+ const updated = db.updateOne(table, id, body, true);
141
+ updated ? json(res, 200, updated) : notFound(res);
142
+ }
143
+
144
+ async function handlePATCH(req, res, route) {
145
+ const { table, id } = route;
146
+ if (id === null) return badRequest(res, 'PATCH requires an id');
147
+
148
+ let body;
149
+ try { body = await readBody(req, res); }
150
+ catch (e) { if (e !== BODY_TOO_LARGE) return badRequest(res, 'Invalid JSON body'); return; }
151
+
152
+ const updated = db.updateOne(table, id, body, false);
153
+ updated ? json(res, 200, updated) : notFound(res);
154
+ }
155
+
156
+ function handleDELETE(_req, res, route) {
157
+ const { table, id } = route;
158
+ if (id === null) return badRequest(res, 'DELETE requires an id');
159
+
160
+ const deleted = db.deleteOne(table, id);
161
+ deleted ? json(res, 200, {}) : notFound(res);
162
+ }
163
+
164
+ function handleHealth(res) {
165
+ json(res, 200, {
166
+ status: 'ok',
167
+ redis: redis.connected ? 'connected' : 'disconnected',
168
+ tables: db.TABLES,
169
+ rateLimit: {
170
+ enabled: rateLimitEnabled,
171
+ max: rateLimitMax,
172
+ windowMs: rateLimitWindowMs,
173
+ },
174
+ });
175
+ }
176
+
177
+ async function requestHandler(req, res) {
178
+ const parsed = new URL(req.url, 'http://localhost');
179
+ const pathname = parsed.pathname;
180
+ const query = parsed.searchParams;
181
+ const method = req.method.toUpperCase();
182
+
183
+ if (method === 'OPTIONS') {
184
+ res.writeHead(204, {
185
+ 'Access-Control-Allow-Origin': '*',
186
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
187
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
188
+ });
189
+ return res.end();
190
+ }
191
+
192
+ if (pathname === '/health' || pathname === '/api/health') {
193
+ return handleHealth(res);
194
+ }
195
+
196
+ if (pathname === '/' || pathname === '/api') {
197
+ return json(res, 200, {
198
+ message: 'json-api-server — JSONPlaceholder-compatible REST API',
199
+ version: '1.0.0',
200
+ endpoints: db.TABLES.map((t) => `/api/${t}`),
201
+ docs: 'GET /health for server status',
202
+ });
203
+ }
204
+
205
+ await new Promise((resolve) => {
206
+ rateLimiter(req, res, resolve);
207
+ });
208
+ if (res.writableEnded) return;
209
+
210
+ const route = parseRoute(pathname);
211
+ if (!route) return notFound(res, `Unknown route: ${pathname}`);
212
+
213
+ try {
214
+ switch (method) {
215
+ case 'GET': return await handleGET(req, res, route, query);
216
+ case 'POST': return await handlePOST(req, res, route);
217
+ case 'PUT': return await handlePUT(req, res, route);
218
+ case 'PATCH': return await handlePATCH(req, res, route);
219
+ case 'DELETE': return handleDELETE(req, res, route);
220
+ default:
221
+ return json(res, 405, { error: `Method ${method} not allowed` });
222
+ }
223
+ } catch (err) {
224
+ console.error('[Error]', err);
225
+ json(res, 500, { error: 'Internal Server Error', message: err.message });
226
+ }
227
+ }
228
+
229
+ const server = http.createServer(requestHandler);
230
+
231
+ function printLog() {
232
+ const rlText = ` Rate limit: ${rateLimitMax} req / ${rateLimitWindowSec}s (${redis.connected ? 'Redis' : 'Memory'})`.padEnd(50);
233
+ console.log(`
234
+ ╔══════════════════════════════════════════════════╗
235
+ ║ nodejs-json-api-server v1.0.0 ║
236
+ ╠══════════════════════════════════════════════════╣
237
+ ║ http://localhost:${port}${' '.repeat(31 - String(port).length)}║
238
+ ║ ║
239
+ ║ Endpoints: ║
240
+ ║ GET /api/users ║
241
+ ║ GET /api/users/:id ║
242
+ ║ GET /api/users/:id/posts ║
243
+ ║ GET /api/posts ║
244
+ ║ GET /api/posts/:id ║
245
+ ║ GET /api/posts/:id/comments ║
246
+ ║ GET /api/comments ║
247
+ ║ GET /api/albums ║
248
+ ║ GET /api/albums/:id/photos ║
249
+ ║ GET /api/photos ║
250
+ ║ GET /api/todos ║
251
+ ║ POST/PUT/PATCH/DELETE on any resource ║
252
+ ║ GET /health ║
253
+ ║ ║
254
+ ║${rlText}║
255
+ ╚══════════════════════════════════════════════════╝
256
+ `.trim());
257
+ }
258
+
259
+ function startServer() {
260
+ server.listen(port, printLog);
261
+ }
262
+
263
+ process.on('SIGINT', () => { server.close(); redis.quit().catch(() => { }); process.exit(0); });
264
+ process.on('SIGTERM', () => { server.close(); redis.quit().catch(() => { }); process.exit(0); });
storage/.gitkeep ADDED
File without changes
tests/test.js ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const http = require('http');
2
+
3
+ const PORT = process.env.PORT || 3000;
4
+
5
+ // Start server in-process
6
+ require('../bin/start');
7
+
8
+ function request(path, method = 'GET', body = null) {
9
+ return new Promise((res, rej) => {
10
+ const opts = { host: '127.0.0.1', port: PORT, path, method, headers: { 'Content-Type': 'application/json' } };
11
+ const req = http.request(opts, r => {
12
+ let d = ''; r.on('data', c => d += c); r.on('end', () => res({ status: r.statusCode, headers: r.headers, body: JSON.parse(d) }));
13
+ });
14
+ req.on('error', rej);
15
+ if (body) req.write(JSON.stringify(body));
16
+ req.end();
17
+ });
18
+ }
19
+
20
+ async function waitForServer() {
21
+ for (let attempt = 0; attempt < 30; attempt++) {
22
+ try {
23
+ await new Promise((resolve, reject) => {
24
+ const req = http.get('http://127.0.0.1:' + PORT + '/health', resolve);
25
+ req.on('error', reject);
26
+ req.end();
27
+ });
28
+ return;
29
+ } catch {
30
+ await new Promise(r => setTimeout(r, 200));
31
+ }
32
+ }
33
+ throw new Error('Server did not start within 6s');
34
+ }
35
+
36
+ async function test() {
37
+ await waitForServer();
38
+ let r;
39
+
40
+ r = await request('/api/users');
41
+ console.log('GET /api/users:', r.status, 'count:', r.body.length);
42
+
43
+ r = await request('/api/users/1');
44
+ console.log('GET /api/users/1:', r.status, 'name:', r.body.name);
45
+
46
+ r = await request('/api/users/1/posts');
47
+ console.log('GET /api/users/1/posts:', r.status, 'count:', r.body.length);
48
+
49
+ r = await request('/api/posts/1/comments');
50
+ console.log('GET /api/posts/1/comments:', r.status, 'count:', r.body.length);
51
+
52
+ r = await request('/api/todos?userId=1&completed=false');
53
+ console.log('GET /api/todos?userId=1&completed=false:', r.status, 'count:', r.body.length);
54
+
55
+ r = await request('/api/posts', 'POST', { userId: 1, title: 'Test post', body: 'Hello world' });
56
+ console.log('POST /api/posts:', r.status, 'id:', r.body.id, 'title:', r.body.title);
57
+ const newId = r.body.id;
58
+
59
+ r = await request('/api/posts/' + newId, 'PATCH', { title: 'Updated title' });
60
+ console.log('PATCH /api/posts/' + newId + ':', r.status, 'title:', r.body.title);
61
+
62
+ r = await request('/api/posts/' + newId, 'DELETE');
63
+ console.log('DELETE /api/posts/' + newId + ':', r.status);
64
+
65
+ // Rate limit headers
66
+ r = await request('/api/users');
67
+ console.log('Rate limit headers:', {
68
+ limit: r.headers['x-ratelimit-limit'],
69
+ remaining: r.headers['x-ratelimit-remaining'],
70
+ store: r.headers['x-ratelimit-store'],
71
+ });
72
+
73
+ // 404 test
74
+ r = await request('/api/users/9999');
75
+ console.log('GET /api/users/9999:', r.status, r.body.error);
76
+ }
77
+
78
+ test().catch(err => { console.error(err); process.exit(1); });
yarn.lock ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
2
+ # yarn lockfile v1
3
+
4
+
5
+ dotenv@^17.4.2:
6
+ version "17.4.2"
7
+ resolved "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz#c07e54a746e11eba021dd9e1047ced5afdc1c034"
8
+ integrity sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==