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

refactor: extract migrate and seed into standalone scripts

Browse files

- Move schema creation into a reusable db/migrate script
- Split data seeding into a separate db/seed script
- Remove implicit migration from server startup

Files changed (6) hide show
  1. README.md +20 -6
  2. package.json +3 -0
  3. src/database.js +1 -123
  4. src/db/migrate.js +77 -0
  5. src/db/seed.js +90 -0
  6. src/server.js +0 -3
README.md CHANGED
@@ -13,7 +13,8 @@ A JSONPlaceholder-compatible REST API built with **Node.js built-ins only** —
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
  ```
@@ -162,7 +163,10 @@ json-api-server/
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/
@@ -172,8 +176,8 @@ json-api-server/
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
@@ -189,9 +193,11 @@ json-api-server/
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
@@ -207,7 +213,7 @@ HTTP Request → CORS headers → Rate limiter → Route parser → Handler →
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)
@@ -223,6 +229,14 @@ sqlite3 storage/data.db < manual/inspect-queries.sql
223
 
224
  This runs comprehensive queries to inspect row counts, column metadata, relationships, integrity checks, and statistics.
225
 
 
 
 
 
 
 
 
 
226
  ---
227
 
228
  ## Testing
 
13
  git clone <repo-url>
14
  cd json-api-server
15
 
16
+ npm run db:setup # create tables + seed data (required before first start)
17
+ npm start # start server
18
  # or with file watching for development:
19
  npm run dev
20
  ```
 
163
  │ ├── config.js # Centralized config — auto-loads dotenv via load-env.js, exports camelCase
164
  │ ├── load-env.js # Shared dotenv loader (auto-run on require, skips in production)
165
  │ ├── server.js # HTTP server, routing, middleware, handlers
166
+ │ ├── database.js # SQLite layer (node:sqlite) — CRUD operations (reads config.js)
167
+ │ ├── db/
168
+ │ │ ├── migrate.js # Table creation (standalone via npm run db:migrate)
169
+ │ │ └── seed.js # Hardcoded seed data (standalone via npm run db:seed)
170
  │ ├── rate-limiter.js # Rate limiter (Redis or in-memory fallback)
171
  │ └── redis.js # Pure-Node Redis client via RESP protocol over TCP
172
  ├── tests/
 
176
  │ └── inspect-queries.sql # SQL queries for database inspection
177
  ├── storage/ # SQLite database files (auto-created)
178
  ├── temp/ # Temporary files (gitignored)
179
+ ├── .env # Base configuration (tried first in development — highest priority)
180
+ ├── .env.dev # Development fallback (tried if .env not found)
181
  ├── .env.test # Test configuration (port 3001, separate DB, no rate limit)
182
  ├── .env.prod.example # Production template (copy to .env.prod)
183
  ├── .env.example # Reference for all available variables
 
193
  bin/start.js → src/load-env.js (loads .env per NODE_ENV, skipped in production)
194
  → src/server.js
195
  ├── src/config.js (centralized config, auto-loads dotenv)
196
+ ├── src/database.js (SQLite CRUD)
197
  ├── src/redis.js (pure RESP + AUTH + URL)
198
  └── src/rate-limiter.js (Redis || in-memory)
199
+
200
+ # Standalone scripts: npm run db:migrate / npm run db:seed / npm run db:setup
201
  ```
202
 
203
  ### Request Flow
 
213
  - **6 tables:** `users`, `posts`, `comments`, `albums`, `photos`, `todos`
214
  - **WAL mode** for better concurrent read performance
215
  - **Foreign keys** enforced via `PRAGMA foreign_keys=ON`
216
+ - **Seed data** initialized via `npm run db:seed` (hardcoded on first run):
217
  - 5 users (with `address` and `company` stored as JSON, parsed on read)
218
  - 50 posts (10 per user)
219
  - 250 comments (5 per post)
 
229
 
230
  This runs comprehensive queries to inspect row counts, column metadata, relationships, integrity checks, and statistics.
231
 
232
+ ### Database Scripts
233
+
234
+ | Script | Command | Description |
235
+ |--------------|--------------------------|-------------------------------------------------------|
236
+ | `db:migrate` | `npm run db:migrate` | Creates the 6 tables (idempotent — uses IF NOT EXISTS) |
237
+ | `db:seed` | `npm run db:seed` | Inserts hardcoded seed data (skips if already seeded) |
238
+ | `db:setup` | `npm run db:setup` | Runs migrate then seed (convenience for first setup) |
239
+
240
  ---
241
 
242
  ## Testing
package.json CHANGED
@@ -9,6 +9,9 @@
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",
 
9
  "url": "https://dangkhoa.dev"
10
  },
11
  "scripts": {
12
+ "db:migrate": "node src/db/migrate.js",
13
+ "db:seed": "node src/db/seed.js",
14
+ "db:setup": "npm run db:migrate && npm run db:seed",
15
  "start": "node bin/start.js",
16
  "prod": "NODE_ENV=production-local node bin/start.js",
17
  "dev": "node --watch bin/start.js",
src/database.js CHANGED
@@ -14,129 +14,7 @@ function getDb() {
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;
@@ -239,4 +117,4 @@ function nextId(table) {
239
  return (row.m || 0) + 1;
240
  }
241
 
242
- module.exports = { migrate, seed, listAll, getOne, insertOne, updateOne, deleteOne, nextId, TABLES };
 
14
  return db;
15
  }
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  function parseRow(table, row) {
20
  if (!row) return null;
 
117
  return (row.m || 0) + 1;
118
  }
119
 
120
+ module.exports = { getDb, listAll, getOne, insertOne, updateOne, deleteOne, nextId, TABLES };
src/db/migrate.js ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ if (require.main === module) {
4
+ const { loadEnv } = require('../load-env');
5
+ loadEnv();
6
+ }
7
+
8
+ const { getDb } = require('../database');
9
+
10
+ function migrate() {
11
+ const d = getDb();
12
+ d.exec(`
13
+ CREATE TABLE IF NOT EXISTS users (
14
+ id INTEGER PRIMARY KEY,
15
+ name TEXT,
16
+ username TEXT UNIQUE,
17
+ email TEXT,
18
+ phone TEXT,
19
+ website TEXT,
20
+ address TEXT,
21
+ company TEXT
22
+ );
23
+
24
+ CREATE TABLE IF NOT EXISTS posts (
25
+ id INTEGER PRIMARY KEY,
26
+ userId INTEGER,
27
+ title TEXT,
28
+ body TEXT,
29
+ FOREIGN KEY(userId) REFERENCES users(id)
30
+ );
31
+
32
+ CREATE TABLE IF NOT EXISTS comments (
33
+ id INTEGER PRIMARY KEY,
34
+ postId INTEGER,
35
+ name TEXT,
36
+ email TEXT,
37
+ body TEXT,
38
+ FOREIGN KEY(postId) REFERENCES posts(id)
39
+ );
40
+
41
+ CREATE TABLE IF NOT EXISTS albums (
42
+ id INTEGER PRIMARY KEY,
43
+ userId INTEGER,
44
+ title TEXT,
45
+ FOREIGN KEY(userId) REFERENCES users(id)
46
+ );
47
+
48
+ CREATE TABLE IF NOT EXISTS photos (
49
+ id INTEGER PRIMARY KEY,
50
+ albumId INTEGER,
51
+ title TEXT,
52
+ url TEXT,
53
+ thumbnailUrl TEXT,
54
+ FOREIGN KEY(albumId) REFERENCES albums(id)
55
+ );
56
+
57
+ CREATE TABLE IF NOT EXISTS todos (
58
+ id INTEGER PRIMARY KEY,
59
+ userId INTEGER,
60
+ title TEXT,
61
+ completed INTEGER DEFAULT 0,
62
+ FOREIGN KEY(userId) REFERENCES users(id)
63
+ );
64
+ `);
65
+ }
66
+
67
+ if (require.main === module) {
68
+ try {
69
+ migrate();
70
+ console.log('[DB] Migration complete.');
71
+ } catch (err) {
72
+ console.error('[DB] Migration failed:', err.message);
73
+ process.exit(1);
74
+ }
75
+ }
76
+
77
+ module.exports = { migrate };
src/db/seed.js ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ if (require.main === module) {
4
+ const { loadEnv } = require('../load-env');
5
+ loadEnv();
6
+ }
7
+
8
+ const { getDb } = require('../database');
9
+
10
+ function seed() {
11
+ const d = getDb();
12
+ const count = d.prepare('SELECT COUNT(*) as c FROM users').get();
13
+ if (count.c > 0) {
14
+ console.log('[DB] Already seeded, skipping.');
15
+ return;
16
+ }
17
+
18
+ console.log('[DB] Seeding initial data…');
19
+
20
+ const users = [
21
+ { 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' }) },
22
+ { 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' }) },
23
+ { 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' }) },
24
+ { 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' }) },
25
+ { 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' }) },
26
+ ];
27
+
28
+ const insertUser = d.prepare(`INSERT INTO users (id,name,username,email,phone,website,address,company) VALUES (?,?,?,?,?,?,?,?)`);
29
+ for (const u of users) {
30
+ insertUser.run(u.id, u.name, u.username, u.email, u.phone, u.website, u.address, u.company);
31
+ }
32
+
33
+ const insertPost = d.prepare(`INSERT INTO posts (id,userId,title,body) VALUES (?,?,?,?)`);
34
+ 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'];
35
+ 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'];
36
+ let postId = 1;
37
+ for (let u = 1; u <= 5; u++) {
38
+ for (let i = 0; i < 10; i++, postId++) {
39
+ insertPost.run(postId, u, titles[i], bodies[i]);
40
+ }
41
+ }
42
+
43
+ const insertComment = d.prepare(`INSERT INTO comments (id,postId,name,email,body) VALUES (?,?,?,?,?)`);
44
+ let commentId = 1;
45
+ for (let p = 1; p <= 50; p++) {
46
+ for (let i = 0; i < 5; i++, commentId++) {
47
+ insertComment.run(commentId, p, `Comment ${i + 1} on post ${p}`, `commenter${commentId}@example.com`, `Great post! Comment body ${commentId}.`);
48
+ }
49
+ }
50
+
51
+ const insertAlbum = d.prepare(`INSERT INTO albums (id,userId,title) VALUES (?,?,?)`);
52
+ 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'];
53
+ let albumId = 1;
54
+ for (let u = 1; u <= 5; u++) {
55
+ for (let i = 0; i < 2; i++, albumId++) {
56
+ insertAlbum.run(albumId, u, albumTitles[(albumId - 1) % albumTitles.length]);
57
+ }
58
+ }
59
+
60
+ const insertPhoto = d.prepare(`INSERT INTO photos (id,albumId,title,url,thumbnailUrl) VALUES (?,?,?,?,?)`);
61
+ let photoId = 1;
62
+ for (let a = 1; a <= 10; a++) {
63
+ for (let i = 0; i < 5; i++, photoId++) {
64
+ insertPhoto.run(photoId, a, `Photo ${photoId}`, `https://via.placeholder.com/600/${photoId}`, `https://via.placeholder.com/150/${photoId}`);
65
+ }
66
+ }
67
+
68
+ const insertTodo = d.prepare(`INSERT INTO todos (id,userId,title,completed) VALUES (?,?,?,?)`);
69
+ const todoTitles = ['delectus aut autem', 'quis ut nam facilis et officia qui', 'fugiat veniam minus', 'et porro tempora'];
70
+ let todoId = 1;
71
+ for (let u = 1; u <= 5; u++) {
72
+ for (let i = 0; i < 4; i++, todoId++) {
73
+ insertTodo.run(todoId, u, todoTitles[i], todoId % 2 === 0 ? 1 : 0);
74
+ }
75
+ }
76
+
77
+ console.log('[DB] Seeding done.');
78
+ }
79
+
80
+ if (require.main === module) {
81
+ try {
82
+ seed();
83
+ process.exit(0);
84
+ } catch (err) {
85
+ console.error('[DB] Seeding failed:', err.message);
86
+ process.exit(1);
87
+ }
88
+ }
89
+
90
+ module.exports = { seed };
src/server.js CHANGED
@@ -8,9 +8,6 @@ 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);
 
8
  const { createRateLimiter } = require('./rate-limiter');
9
  const db = require('./database');
10
 
 
 
 
11
  const redis = new RedisClient(redisOpts);
12
 
13
  const rateLimiter = createRateLimiter(redis);