Spaces:
Sleeping
Sleeping
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
- .env.example +4 -0
- .env.prod.example +13 -0
- .env.test +12 -0
- README.md +13 -11
- package.json +1 -1
- src/db/migrate.js +4 -4
- 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 #
|
| 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**
|
| 217 |
-
-
|
| 218 |
-
-
|
| 219 |
-
-
|
| 220 |
-
-
|
| 221 |
-
-
|
| 222 |
-
-
|
| 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 (
|
| 237 |
-
| `db:seed` | `npm run db:seed` |
|
| 238 |
-
| `db:setup` | `npm run db:setup` | Runs
|
| 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:
|
| 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
|
| 12 |
-
|
| 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 (
|
| 72 |
-
console.error('[DB] Migration failed:',
|
| 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 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
console.log('[DB] Already seeded, skipping.');
|
| 15 |
return;
|
| 16 |
}
|
| 17 |
|
| 18 |
-
|
| 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 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
insertPost.run(postId, u, titles[i], bodies[i]);
|
| 40 |
}
|
| 41 |
-
}
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
| 48 |
}
|
| 49 |
-
}
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
for (
|
| 56 |
-
insertAlbum.run(
|
| 57 |
}
|
| 58 |
-
}
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
| 65 |
}
|
| 66 |
-
}
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
for (
|
| 73 |
-
insertTodo.run(
|
| 74 |
}
|
| 75 |
-
}
|
| 76 |
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
}
|
| 79 |
|
| 80 |
if (require.main === module) {
|
| 81 |
-
|
| 82 |
-
|
| 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 };
|