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

feat: fetch seed data from JSONPlaceholder API

Browse files

- Replace hardcoded sample data with live data from JSONPlaceholder
- Add fallback logging when the remote fetch fails

Files changed (7) hide show
  1. .env.example +4 -0
  2. .env.prod.example +13 -0
  3. .env.test +12 -0
  4. README.md +13 -11
  5. package.json +1 -1
  6. src/db/migrate.js +4 -4
  7. src/db/seed.js +70 -58
.env.example CHANGED
@@ -29,6 +29,10 @@ 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
 
29
  REDIS_DB=0
30
  # REDIS_PASSWORD=your-password
31
 
32
+ # Seed data source (JSONPlaceholder-compatible API)
33
+ # Override to use a different data source for seeding
34
+ # SEED_API_BASE_URL=https://jsonplaceholder.typicode.com
35
+
36
  # Rate limiting
37
  RATE_LIMIT_ENABLED=true
38
  RATE_LIMIT_MAX=100
.env.prod.example CHANGED
@@ -1,15 +1,28 @@
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
 
1
  # ─── Production configuration ───────────────────────────────────────────────────
2
  # Loaded when NODE_ENV=production
3
  # Uncomment and fill in your production values:
4
+
5
+ # Server
6
  # PORT=8080
7
+
8
+ # SQLite database path (relative to project root)
9
  # DB_PATH=./storage/prod.db
10
 
11
+ # Redis (optional — rate limiting falls back to in-memory if unavailable)
12
+ # Option A: connection URL (takes priority over individual settings below)
13
+ # Useful for cloud providers (Upstash, Redis Cloud, etc.)
14
  # REDIS_URL=redis://user:password@your-cloud-redis:6379/0
15
+
16
+ # Option B: individual settings
17
  # REDIS_HOST=127.0.0.1
18
  # REDIS_PORT=6379
19
  # REDIS_DB=0
20
  # REDIS_PASSWORD=
21
 
22
+ # Seed data source (JSONPlaceholder-compatible API)
23
+ # Override to use a different data source for seeding
24
+ # SEED_API_BASE_URL=https://jsonplaceholder.typicode.com
25
+
26
  # Rate limiting
27
  # RATE_LIMIT_ENABLED=true
28
  # RATE_LIMIT_MAX=1000
.env.test CHANGED
@@ -1,15 +1,27 @@
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
 
1
  # ─── Test configuration ─────────────────────────────────────────────────────────
2
  # Loaded when NODE_ENV=test
3
+
4
+ # Server
5
  PORT=3001
6
+
7
+ # SQLite database path (relative to project root)
8
  DB_PATH=./storage/test.db
9
 
10
  # Redis (optional — rate limiting falls back to in-memory if unavailable)
11
+ # Option A: connection URL (takes priority over individual settings below)
12
+ # Useful for cloud providers (Upstash, Redis Cloud, etc.)
13
  # REDIS_URL=
14
+
15
+ # Option B: individual settings
16
  # REDIS_HOST=127.0.0.1
17
  # REDIS_PORT=6379
18
  # REDIS_DB=0
19
  # REDIS_PASSWORD=
20
 
21
+ # Seed data source (JSONPlaceholder-compatible API)
22
+ # Override to use a different data source for seeding
23
+ # SEED_API_BASE_URL=https://jsonplaceholder.typicode.com
24
+
25
  # Rate limiting
26
  RATE_LIMIT_ENABLED=true
27
  # RATE_LIMIT_MAX=100
README.md CHANGED
@@ -50,6 +50,7 @@ Environment files are loaded by `src/load-env.js` (auto-run via `src/config.js`)
50
  | `RATE_LIMIT_ENABLED` | `true` | Enable/disable rate limiting |
51
  | `RATE_LIMIT_MAX` | `100` | Max requests per time window |
52
  | `RATE_LIMIT_WINDOW_MS` | `60000` | Time window in milliseconds (default 1 min) |
 
53
 
54
  ---
55
 
@@ -166,7 +167,7 @@ json-api-server/
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/
@@ -213,13 +214,13 @@ HTTP Request → CORS headers → Rate limiter → Route parser → Handler →
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)
220
- - 10 albums (2 per user)
221
- - 50 photos (5 per album)
222
- - 20 todos (4 per user, `completed` stored as 0/1 integer, returned as boolean)
223
 
224
  ### Helper Script
225
 
@@ -233,9 +234,9 @@ This runs comprehensive queries to inspect row counts, column metadata, relation
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
 
@@ -261,6 +262,7 @@ The integration test automatically verifies all endpoints, including CRUD operat
261
  - **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.
262
  - **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.
263
  - **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.
 
264
  - **CORS** enabled on all routes
265
  - **Graceful shutdown** — handles `SIGINT` and `SIGTERM` to close the server and Redis connection cleanly
266
 
 
50
  | `RATE_LIMIT_ENABLED` | `true` | Enable/disable rate limiting |
51
  | `RATE_LIMIT_MAX` | `100` | Max requests per time window |
52
  | `RATE_LIMIT_WINDOW_MS` | `60000` | Time window in milliseconds (default 1 min) |
53
+ | `SEED_API_BASE_URL` | `https://jsonplaceholder.typicode.com` | Base URL for seed data API |
54
 
55
  ---
56
 
 
167
  │ ├── database.js # SQLite layer (node:sqlite) — CRUD operations (reads config.js)
168
  │ ├── db/
169
  │ │ ├── migrate.js # Table creation (standalone via npm run db:migrate)
170
+ │ │ └── seed.js # Fetches seed data from [JSONPlaceholder](https://jsonplaceholder.typicode.com) API, auto-runs migrate
171
  │ ├── rate-limiter.js # Rate limiter (Redis or in-memory fallback)
172
  │ └── redis.js # Pure-Node Redis client via RESP protocol over TCP
173
  ├── tests/
 
214
  - **6 tables:** `users`, `posts`, `comments`, `albums`, `photos`, `todos`
215
  - **WAL mode** for better concurrent read performance
216
  - **Foreign keys** enforced via `PRAGMA foreign_keys=ON`
217
+ - **Seed data** fetched from [JSONPlaceholder](https://jsonplaceholder.typicode.com) on first run:
218
+ - 10 users (with `address` and `company` stored as JSON, parsed on read)
219
+ - 100 posts
220
+ - 500 comments
221
+ - 100 albums
222
+ - 5000 photos
223
+ - 200 todos
224
 
225
  ### Helper Script
226
 
 
234
 
235
  | Script | Command | Description |
236
  |--------------|--------------------------|-------------------------------------------------------|
237
+ | `db:migrate` | `npm run db:migrate` | Creates the 6 tables (loads dotenv when run standalone) |
238
+ | `db:seed` | `npm run db:seed` | Fetches seed data from [JSONPlaceholder](https://jsonplaceholder.typicode.com), auto-runs migrate |
239
+ | `db:setup` | `npm run db:setup` | Runs `db:seed` (which internally calls migrate) |
240
 
241
  ---
242
 
 
262
  - **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.
263
  - **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.
264
  - **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.
265
+ - **Testable seed script** — `src/db/seed.js` accepts `database` and `fetch` parameters via dependency injection, enabling full unit testing without mocking `require()`.
266
  - **CORS** enabled on all routes
267
  - **Graceful shutdown** — handles `SIGINT` and `SIGTERM` to close the server and Redis connection cleanly
268
 
package.json CHANGED
@@ -11,7 +11,7 @@
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",
 
11
  "scripts": {
12
  "db:migrate": "node src/db/migrate.js",
13
  "db:seed": "node src/db/seed.js",
14
+ "db:setup": "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/db/migrate.js CHANGED
@@ -8,8 +8,8 @@ if (require.main === module) {
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,
@@ -68,8 +68,8 @@ 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
  }
 
8
  const { getDb } = require('../database');
9
 
10
  function migrate() {
11
+ const db = getDb();
12
+ db.exec(`
13
  CREATE TABLE IF NOT EXISTS users (
14
  id INTEGER PRIMARY KEY,
15
  name TEXT,
 
68
  try {
69
  migrate();
70
  console.log('[DB] Migration complete.');
71
+ } catch (error) {
72
+ console.error('[DB] Migration failed:', error.message);
73
  process.exit(1);
74
  }
75
  }
src/db/seed.js CHANGED
@@ -6,85 +6,97 @@ if (require.main === module) {
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 };
 
6
  }
7
 
8
  const { getDb } = require('../database');
9
+ const { migrate } = require('./migrate');
10
 
11
+ const BASE = process.env.SEED_API_BASE_URL || 'https://jsonplaceholder.typicode.com';
12
+
13
+ async function fetchJSON(url) {
14
+ const res = await fetch(url);
15
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
16
+ return res.json();
17
+ }
18
+
19
+ async function seed({ database = getDb(), fetch: fetchFn = fetchJSON, runMigrate = true } = {}) {
20
+ if (runMigrate) migrate();
21
+ const db = database;
22
+ const row = db.prepare('SELECT COUNT(*) as rowCount FROM users').get();
23
+ if (row.rowCount > 0) {
24
  console.log('[DB] Already seeded, skipping.');
25
  return;
26
  }
27
 
28
+ const t0 = Date.now();
29
+ db.exec('BEGIN');
 
 
 
 
 
 
 
30
 
31
+ try {
32
+ console.log(' [fetch] GET /users');
33
+ const t1 = Date.now();
34
+ const users = await fetchFn(`${BASE}/users`);
35
+ const insertUser = db.prepare(`INSERT INTO users (id,name,username,email,phone,website,address,company) VALUES (?,?,?,?,?,?,?,?)`);
36
+ for (const user of users) {
37
+ insertUser.run(user.id, user.name, user.username, user.email, user.phone, user.website, JSON.stringify(user.address), JSON.stringify(user.company));
38
+ }
39
+ console.log(` [done] users: ${users.length} rows in ${Date.now() - t1}ms`);
40
 
41
+ console.log(' [fetch] GET /posts');
42
+ const t2 = Date.now();
43
+ const posts = await fetchFn(`${BASE}/posts`);
44
+ const insertPost = db.prepare(`INSERT INTO posts (id,userId,title,body) VALUES (?,?,?,?)`);
45
+ for (const post of posts) {
46
+ insertPost.run(post.id, post.userId, post.title, post.body);
 
47
  }
48
+ console.log(` [done] posts: ${posts.length} rows in ${Date.now() - t2}ms`);
49
 
50
+ console.log(' [fetch] GET /comments');
51
+ const t3 = Date.now();
52
+ const comments = await fetchFn(`${BASE}/comments`);
53
+ const insertComment = db.prepare(`INSERT INTO comments (id,postId,name,email,body) VALUES (?,?,?,?,?)`);
54
+ for (const comment of comments) {
55
+ insertComment.run(comment.id, comment.postId, comment.name, comment.email, comment.body);
56
  }
57
+ console.log(` [done] comments: ${comments.length} rows in ${Date.now() - t3}ms`);
58
 
59
+ console.log(' [fetch] GET /albums');
60
+ const t4 = Date.now();
61
+ const albums = await fetchFn(`${BASE}/albums`);
62
+ const insertAlbum = db.prepare(`INSERT INTO albums (id,userId,title) VALUES (?,?,?)`);
63
+ for (const album of albums) {
64
+ insertAlbum.run(album.id, album.userId, album.title);
65
  }
66
+ console.log(` [done] albums: ${albums.length} rows in ${Date.now() - t4}ms`);
67
 
68
+ console.log(' [fetch] GET /photos');
69
+ const t5 = Date.now();
70
+ const photos = await fetchFn(`${BASE}/photos`);
71
+ const insertPhoto = db.prepare(`INSERT INTO photos (id,albumId,title,url,thumbnailUrl) VALUES (?,?,?,?,?)`);
72
+ for (const photo of photos) {
73
+ insertPhoto.run(photo.id, photo.albumId, photo.title, photo.url, photo.thumbnailUrl);
74
  }
75
+ console.log(` [done] photos: ${photos.length} rows in ${Date.now() - t5}ms`);
76
 
77
+ console.log(' [fetch] GET /todos');
78
+ const t6 = Date.now();
79
+ const todos = await fetchFn(`${BASE}/todos`);
80
+ const insertTodo = db.prepare(`INSERT INTO todos (id,userId,title,completed) VALUES (?,?,?,?)`);
81
+ for (const todo of todos) {
82
+ insertTodo.run(todo.id, todo.userId, todo.title, todo.completed ? 1 : 0);
83
  }
84
+ console.log(` [done] todos: ${todos.length} rows in ${Date.now() - t6}ms`);
85
 
86
+ db.exec('COMMIT');
87
+ console.log(`[DB] Seeding done in ${Date.now() - t0}ms`);
88
+ } catch (error) {
89
+ db.exec('ROLLBACK');
90
+ console.error('[DB] Seeding failed:', error.message);
91
+ throw error;
92
+ }
93
  }
94
 
95
  if (require.main === module) {
96
+ seed().then(() => process.exit(0)).catch((error) => {
97
+ console.error('[DB] Seeding failed:', error.message);
 
 
 
98
  process.exit(1);
99
+ });
100
  }
101
 
102
  module.exports = { seed };