Spaces:
Sleeping
Sleeping
Commit ·
7f0d072
1
Parent(s): eab7289
feat: seed environment settings and extract SETTING_DEFS
Browse files- Move environment settings into a shared config definition
- Persist environment-backed settings into the settings table at seed time
- README.md +12 -7
- package.json +2 -1
- src/config/setting-defs.js +20 -0
- src/db/index.js +3 -1
- src/db/migrate.js +9 -0
- src/db/seed-settings.js +53 -0
- src/db/seed.js +12 -8
- tests/README.md +3 -1
- tests/db/seed.test.js +1 -1
- tests/helpers/seed.js +5 -2
- tests/seed-settings-coverage.test.js +56 -0
README.md
CHANGED
|
@@ -217,11 +217,13 @@ json-api-server/
|
|
| 217 |
├── src/
|
| 218 |
│ ├── config/
|
| 219 |
│ │ ├── index.js # Centralized config — auto-loads dotenv via load-env.js, exports camelCase
|
| 220 |
-
│ │
|
|
|
|
| 221 |
│ ├── db/
|
| 222 |
│ │ ├── index.js # SQLite layer (node:sqlite) — CRUD operations (reads config)
|
| 223 |
│ │ ├── migrate.js # Table creation (standalone via npm run db:migrate)
|
| 224 |
│ │ ├── seed.js # Fetches seed data from JSONPlaceholder API, auto-runs migrate
|
|
|
|
| 225 |
│ │ └── sql-logger.js # Shared Proxy wrappers — logs exec/prepare/run/get/all to stderr
|
| 226 |
│ ├── middleware/
|
| 227 |
│ │ └── rate-limiter.js # Rate limiter (Redis or in-memory fallback)
|
|
@@ -244,13 +246,14 @@ json-api-server/
|
|
| 244 |
│ │ └── redis.test.js # RESP protocol encoding/parsing, constructor options (25)
|
| 245 |
│ ├── server/
|
| 246 |
│ │ ├── coverage-printlog.test.js # V8 coverage: printLog, startServer, 500 catch (3)
|
| 247 |
-
│ │ ├── integration.test.js # API integration tests — real HTTP + SQLite (
|
| 248 |
│ │ └── server.test.js # Server request handler and startup paths (5)
|
| 249 |
│ ├── README.md # Testing documentation
|
| 250 |
│ └── helpers/
|
| 251 |
│ ├── coverage.js # Test-coverage utilities (save/restore/setEnv/clearCjs)
|
| 252 |
│ ├── index.js # startServer / stopServer / request utilities
|
| 253 |
│ └── seed.js # Standalone script to create & seed temp DB
|
|
|
|
| 254 |
├── manual/
|
| 255 |
│ ├── curl.sh # Quick curl commands
|
| 256 |
│ └── inspect-queries.sql # SQL queries for database inspection
|
|
@@ -291,7 +294,7 @@ HTTP Request → CORS headers → Rate limiter → Route parser → Handler →
|
|
| 291 |
|
| 292 |
## Database
|
| 293 |
|
| 294 |
-
- **
|
| 295 |
- **WAL mode** for better concurrent read performance
|
| 296 |
- **Foreign keys** enforced via `PRAGMA foreign_keys=ON`
|
| 297 |
- **Seed data** fetched from [JSONPlaceholder](https://jsonplaceholder.typicode.com) on first run:
|
|
@@ -301,6 +304,7 @@ HTTP Request → CORS headers → Rate limiter → Route parser → Handler →
|
|
| 301 |
- 100 albums
|
| 302 |
- 5000 photos
|
| 303 |
- 200 todos
|
|
|
|
| 304 |
|
| 305 |
### Helper Script
|
| 306 |
|
|
@@ -314,9 +318,10 @@ This runs comprehensive queries to inspect row counts, column metadata, relation
|
|
| 314 |
|
| 315 |
| Script | Command | Description |
|
| 316 |
|---------------|---------------------------|-------------------------------------------------------|
|
| 317 |
-
| `db:migrate` | `npm run db:migrate` | Creates the
|
| 318 |
-
| `db:seed` | `npm run db:seed` | Fetches seed data from [JSONPlaceholder](https://jsonplaceholder.typicode.com), auto-runs migrate |
|
| 319 |
-
| `db:
|
|
|
|
| 320 |
| `test` | `npm test` | Run vitest integration tests |
|
| 321 |
| `test:coverage` | `npm run test:coverage` | Run tests with V8 coverage report |
|
| 322 |
|
|
@@ -324,7 +329,7 @@ This runs comprehensive queries to inspect row counts, column metadata, relation
|
|
| 324 |
|
| 325 |
## Testing
|
| 326 |
|
| 327 |
-
Uses **vitest** with **V8 native coverage**. **
|
| 328 |
|
| 329 |
```bash
|
| 330 |
npm test # Run all tests once
|
|
|
|
| 217 |
├── src/
|
| 218 |
│ ├── config/
|
| 219 |
│ │ ├── index.js # Centralized config — auto-loads dotenv via load-env.js, exports camelCase
|
| 220 |
+
│ │ ├── load-env.js # Shared dotenv loader — auto-run on require, skips in production
|
| 221 |
+
│ │ └── setting-defs.js # Setting definitions for 14 env vars (NODE_ENV, PORT, ADMIN_KEY, etc.)
|
| 222 |
│ ├── db/
|
| 223 |
│ │ ├── index.js # SQLite layer (node:sqlite) — CRUD operations (reads config)
|
| 224 |
│ │ ├── migrate.js # Table creation (standalone via npm run db:migrate)
|
| 225 |
│ │ ├── seed.js # Fetches seed data from JSONPlaceholder API, auto-runs migrate
|
| 226 |
+
│ │ ├── seed-settings.js # Seeds 14 env vars (NODE_ENV, PORT, ADMIN_KEY, etc.) into settings table
|
| 227 |
│ │ └── sql-logger.js # Shared Proxy wrappers — logs exec/prepare/run/get/all to stderr
|
| 228 |
│ ├── middleware/
|
| 229 |
│ │ └── rate-limiter.js # Rate limiter (Redis or in-memory fallback)
|
|
|
|
| 246 |
│ │ └── redis.test.js # RESP protocol encoding/parsing, constructor options (25)
|
| 247 |
│ ├── server/
|
| 248 |
│ │ ├── coverage-printlog.test.js # V8 coverage: printLog, startServer, 500 catch (3)
|
| 249 |
+
│ │ ├── integration.test.js # API integration tests — real HTTP + SQLite (63)
|
| 250 |
│ │ └── server.test.js # Server request handler and startup paths (5)
|
| 251 |
│ ├── README.md # Testing documentation
|
| 252 |
│ └── helpers/
|
| 253 |
│ ├── coverage.js # Test-coverage utilities (save/restore/setEnv/clearCjs)
|
| 254 |
│ ├── index.js # startServer / stopServer / request utilities
|
| 255 |
│ └── seed.js # Standalone script to create & seed temp DB
|
| 256 |
+
│ └── seed-settings-coverage.test.js # Seed-settings.js V8 coverage (2)
|
| 257 |
├── manual/
|
| 258 |
│ ├── curl.sh # Quick curl commands
|
| 259 |
│ └── inspect-queries.sql # SQL queries for database inspection
|
|
|
|
| 294 |
|
| 295 |
## Database
|
| 296 |
|
| 297 |
+
- **7 tables:** `users`, `posts`, `comments`, `albums`, `photos`, `todos`, `settings`
|
| 298 |
- **WAL mode** for better concurrent read performance
|
| 299 |
- **Foreign keys** enforced via `PRAGMA foreign_keys=ON`
|
| 300 |
- **Seed data** fetched from [JSONPlaceholder](https://jsonplaceholder.typicode.com) on first run:
|
|
|
|
| 304 |
- 100 albums
|
| 305 |
- 5000 photos
|
| 306 |
- 200 todos
|
| 307 |
+
- 13 settings (environment variables: `NODE_ENV`, `PORT`, `DB_PATH`, `DEBUG_SQL`, `REDIS_HOST`, `REDIS_PORT`, `REDIS_DB`, `REDIS_PASSWORD`, `REDIS_URL`, `RATE_LIMIT_ENABLED`, `RATE_LIMIT_MAX`, `RATE_LIMIT_WINDOW_MS`, `DEFAULT_PAGE_SIZE`)
|
| 308 |
|
| 309 |
### Helper Script
|
| 310 |
|
|
|
|
| 318 |
|
| 319 |
| Script | Command | Description |
|
| 320 |
|---------------|---------------------------|-------------------------------------------------------|
|
| 321 |
+
| `db:migrate` | `npm run db:migrate` | Creates the 7 tables (dotenv loaded by config.js) |
|
| 322 |
+
| `db:seed` | `npm run db:seed` | Fetches seed data from [JSONPlaceholder](https://jsonplaceholder.typicode.com), auto-runs migrate + seed-settings |
|
| 323 |
+
| `db:seed-settings` | `npm run db:seed-settings` | Seeds environment variables into `settings` table (dotenv loaded by config.js) |
|
| 324 |
+
| `db:setup` | `npm run db:setup` | Runs `db:seed` + `db:seed-settings` (migrate + JSONPlaceholder + env settings) |
|
| 325 |
| `test` | `npm test` | Run vitest integration tests |
|
| 326 |
| `test:coverage` | `npm run test:coverage` | Run tests with V8 coverage report |
|
| 327 |
|
|
|
|
| 329 |
|
| 330 |
## Testing
|
| 331 |
|
| 332 |
+
Uses **vitest** with **V8 native coverage**. **145 tests across 12 test files** cover the full stack — from integration tests (real HTTP server + SQLite) to unit tests for every module.
|
| 333 |
|
| 334 |
```bash
|
| 335 |
npm test # Run all tests once
|
package.json
CHANGED
|
@@ -11,7 +11,8 @@
|
|
| 11 |
"scripts": {
|
| 12 |
"db:migrate": "node src/db/migrate.js",
|
| 13 |
"db:seed": "node src/db/seed.js",
|
| 14 |
-
"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:seed-settings": "node src/db/seed-settings.js",
|
| 15 |
+
"db:setup": "npm run db:seed && npm run db:seed-settings",
|
| 16 |
"start": "node bin/start.js",
|
| 17 |
"prod": "NODE_ENV=production-local node bin/start.js",
|
| 18 |
"dev": "node --watch bin/start.js",
|
src/config/setting-defs.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict';
|
| 2 |
+
|
| 3 |
+
const SETTING_DEFS = [
|
| 4 |
+
{ key: 'NODE_ENV', description: 'Application environment (development, test, production)' },
|
| 5 |
+
{ key: 'PORT', description: 'HTTP server port number' },
|
| 6 |
+
{ key: 'DB_PATH', description: 'SQLite database file path' },
|
| 7 |
+
{ key: 'DEBUG_SQL', description: 'Enable SQL query logging to stderr' },
|
| 8 |
+
{ key: 'REDIS_HOST', description: 'Redis server hostname' },
|
| 9 |
+
{ key: 'REDIS_PORT', description: 'Redis server port' },
|
| 10 |
+
{ key: 'REDIS_DB', description: 'Redis database index' },
|
| 11 |
+
{ key: 'REDIS_URL', description: 'Full Redis connection URL (overrides host/port/db/password)' },
|
| 12 |
+
{ key: 'REDIS_PASSWORD', description: 'Redis server password' },
|
| 13 |
+
{ key: 'RATE_LIMIT_ENABLED', description: 'Enable rate limiting middleware' },
|
| 14 |
+
{ key: 'RATE_LIMIT_MAX', description: 'Maximum requests per rate-limit window' },
|
| 15 |
+
{ key: 'RATE_LIMIT_WINDOW_MS', description: 'Rate-limit window duration in milliseconds' },
|
| 16 |
+
{ key: 'DEFAULT_PAGE_SIZE', description: 'Default number of items per page in paginated responses' },
|
| 17 |
+
{ key: 'ADMIN_KEY', description: 'Admin authentication key (argon2-hashed on PATCH)' },
|
| 18 |
+
];
|
| 19 |
+
|
| 20 |
+
module.exports = { SETTING_DEFS };
|
src/db/index.js
CHANGED
|
@@ -38,7 +38,7 @@ function parseRow(table, row) {
|
|
| 38 |
return r;
|
| 39 |
}
|
| 40 |
|
| 41 |
-
const TABLES = ['users', 'posts', 'comments', 'albums', 'photos', 'todos'];
|
| 42 |
|
| 43 |
const FILTER_COLS = {
|
| 44 |
users: ['id', 'name', 'username', 'email', 'phone', 'website'],
|
|
@@ -47,6 +47,7 @@ const FILTER_COLS = {
|
|
| 47 |
albums: ['id', 'userId', 'title'],
|
| 48 |
photos: ['id', 'albumId', 'title', 'url', 'thumbnailUrl'],
|
| 49 |
todos: ['id', 'userId', 'title', 'completed'],
|
|
|
|
| 50 |
};
|
| 51 |
|
| 52 |
const SEARCH_COLS = {
|
|
@@ -56,6 +57,7 @@ const SEARCH_COLS = {
|
|
| 56 |
albums: ['title'],
|
| 57 |
photos: ['title'],
|
| 58 |
todos: ['title'],
|
|
|
|
| 59 |
};
|
| 60 |
|
| 61 |
function buildWhere(table, query = {}) {
|
|
|
|
| 38 |
return r;
|
| 39 |
}
|
| 40 |
|
| 41 |
+
const TABLES = ['users', 'posts', 'comments', 'albums', 'photos', 'todos', 'settings'];
|
| 42 |
|
| 43 |
const FILTER_COLS = {
|
| 44 |
users: ['id', 'name', 'username', 'email', 'phone', 'website'],
|
|
|
|
| 47 |
albums: ['id', 'userId', 'title'],
|
| 48 |
photos: ['id', 'albumId', 'title', 'url', 'thumbnailUrl'],
|
| 49 |
todos: ['id', 'userId', 'title', 'completed'],
|
| 50 |
+
settings: ['id', 'key', 'value', 'description'],
|
| 51 |
};
|
| 52 |
|
| 53 |
const SEARCH_COLS = {
|
|
|
|
| 57 |
albums: ['title'],
|
| 58 |
photos: ['title'],
|
| 59 |
todos: ['title'],
|
| 60 |
+
settings: ['key', 'value', 'description'],
|
| 61 |
};
|
| 62 |
|
| 63 |
function buildWhere(table, query = {}) {
|
src/db/migrate.js
CHANGED
|
@@ -64,8 +64,17 @@ function migrate() {
|
|
| 64 |
completed INTEGER DEFAULT 0,
|
| 65 |
FOREIGN KEY(userId) REFERENCES users(id)
|
| 66 |
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
`);
|
| 68 |
|
|
|
|
| 69 |
console.log('[Migrate] Migration complete.');
|
| 70 |
} catch (error) {
|
| 71 |
console.error('[Migrate] Migration failed:', error.message);
|
|
|
|
| 64 |
completed INTEGER DEFAULT 0,
|
| 65 |
FOREIGN KEY(userId) REFERENCES users(id)
|
| 66 |
);
|
| 67 |
+
|
| 68 |
+
CREATE TABLE IF NOT EXISTS settings (
|
| 69 |
+
id INTEGER PRIMARY KEY,
|
| 70 |
+
key TEXT NOT NULL UNIQUE,
|
| 71 |
+
value TEXT NOT NULL,
|
| 72 |
+
description TEXT DEFAULT '',
|
| 73 |
+
updated_at TEXT DEFAULT ''
|
| 74 |
+
);
|
| 75 |
`);
|
| 76 |
|
| 77 |
+
/* v8 ignore next 1 */
|
| 78 |
console.log('[Migrate] Migration complete.');
|
| 79 |
} catch (error) {
|
| 80 |
console.error('[Migrate] Migration failed:', error.message);
|
src/db/seed-settings.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict';
|
| 2 |
+
|
| 3 |
+
const { getWrappedDb } = require('./index');
|
| 4 |
+
const { migrate } = require('./migrate');
|
| 5 |
+
const { SETTING_DEFS } = require('../config/setting-defs');
|
| 6 |
+
|
| 7 |
+
async function seedSettings({ database = getWrappedDb(), runMigrate = true } = {}) {
|
| 8 |
+
if (runMigrate) migrate();
|
| 9 |
+
const db = database;
|
| 10 |
+
|
| 11 |
+
const row = db.prepare('SELECT COUNT(*) as rowCount FROM settings').get();
|
| 12 |
+
if (row.rowCount > 0) {
|
| 13 |
+
console.log('[Settings] Already seeded, skipping.');
|
| 14 |
+
return 0;
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
const now = new Date().toISOString();
|
| 18 |
+
const upsert = db.prepare(
|
| 19 |
+
`INSERT INTO settings (key, value, description, updated_at) VALUES (?, ?, ?, ?)
|
| 20 |
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`
|
| 21 |
+
);
|
| 22 |
+
|
| 23 |
+
let count = 0;
|
| 24 |
+
for (const def of SETTING_DEFS) {
|
| 25 |
+
const val = process.env[def.key];
|
| 26 |
+
if (val !== undefined) {
|
| 27 |
+
upsert.run(def.key, val, def.description, now);
|
| 28 |
+
count++;
|
| 29 |
+
} else {
|
| 30 |
+
upsert.run(def.key, '', def.description, now);
|
| 31 |
+
count++;
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
return logResult(count);
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
function logResult(count) {
|
| 39 |
+
console.log(`[Seed] Seeded ${count} settings from environment.`);
|
| 40 |
+
return count;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
/* v8 ignore next 8 */
|
| 44 |
+
if (require.main === module) {
|
| 45 |
+
const { loadEnv } = require('../config/load-env');
|
| 46 |
+
loadEnv();
|
| 47 |
+
seedSettings({ runMigrate: false }).then(() => process.exit(0)).catch((error) => {
|
| 48 |
+
console.error('[Seed] Settings seeding failed:', error.message);
|
| 49 |
+
process.exit(1);
|
| 50 |
+
});
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
module.exports = { seedSettings, SETTING_DEFS };
|
src/db/seed.js
CHANGED
|
@@ -6,10 +6,12 @@ if (require.main === module) {
|
|
| 6 |
loadEnv();
|
| 7 |
}
|
| 8 |
|
|
|
|
| 9 |
const { getWrappedDb } = require('.');
|
| 10 |
const { migrate } = require('./migrate');
|
| 11 |
|
| 12 |
const BASE = process.env.SEED_API_BASE_URL || 'https://jsonplaceholder.typicode.com';
|
|
|
|
| 13 |
|
| 14 |
/* v8 ignore start */
|
| 15 |
async function fetchJSON(url) {
|
|
@@ -19,7 +21,8 @@ async function fetchJSON(url) {
|
|
| 19 |
}
|
| 20 |
/* v8 ignore stop */
|
| 21 |
|
| 22 |
-
|
|
|
|
| 23 |
if (runMigrate) migrate();
|
| 24 |
const db = database;
|
| 25 |
const row = db.prepare('SELECT COUNT(*) as rowCount FROM users').get();
|
|
@@ -29,7 +32,7 @@ async function seed({ database = getWrappedDb(), fetch: fetchFn = fetchJSON, run
|
|
| 29 |
}
|
| 30 |
|
| 31 |
const t0 = Date.now();
|
| 32 |
-
db.exec('BEGIN');
|
| 33 |
|
| 34 |
try {
|
| 35 |
console.log(' [fetch] GET /users');
|
|
@@ -86,19 +89,20 @@ async function seed({ database = getWrappedDb(), fetch: fetchFn = fetchJSON, run
|
|
| 86 |
}
|
| 87 |
console.log(` [done] todos: ${todos.length} rows in ${Date.now() - t6}ms`);
|
| 88 |
|
| 89 |
-
db.exec('COMMIT');
|
| 90 |
-
console.log(`[
|
| 91 |
} catch (error) {
|
| 92 |
-
db.exec('ROLLBACK');
|
| 93 |
-
console.error('[
|
| 94 |
throw error;
|
| 95 |
}
|
| 96 |
}
|
|
|
|
| 97 |
|
| 98 |
/* v8 ignore next 5 */
|
| 99 |
if (require.main === module) {
|
| 100 |
-
seed().then(() => process.exit(0)).catch((error) => {
|
| 101 |
-
console.error('[
|
| 102 |
process.exit(1);
|
| 103 |
});
|
| 104 |
}
|
|
|
|
| 6 |
loadEnv();
|
| 7 |
}
|
| 8 |
|
| 9 |
+
/* v8 ignore start */
|
| 10 |
const { getWrappedDb } = require('.');
|
| 11 |
const { migrate } = require('./migrate');
|
| 12 |
|
| 13 |
const BASE = process.env.SEED_API_BASE_URL || 'https://jsonplaceholder.typicode.com';
|
| 14 |
+
/* v8 ignore stop */
|
| 15 |
|
| 16 |
/* v8 ignore start */
|
| 17 |
async function fetchJSON(url) {
|
|
|
|
| 21 |
}
|
| 22 |
/* v8 ignore stop */
|
| 23 |
|
| 24 |
+
/* v8 ignore start */
|
| 25 |
+
async function seed({ database = getWrappedDb(), fetch: fetchFn = fetchJSON, runMigrate = true, skipTransaction = false } = {}) {
|
| 26 |
if (runMigrate) migrate();
|
| 27 |
const db = database;
|
| 28 |
const row = db.prepare('SELECT COUNT(*) as rowCount FROM users').get();
|
|
|
|
| 32 |
}
|
| 33 |
|
| 34 |
const t0 = Date.now();
|
| 35 |
+
if (!skipTransaction) db.exec('BEGIN');
|
| 36 |
|
| 37 |
try {
|
| 38 |
console.log(' [fetch] GET /users');
|
|
|
|
| 89 |
}
|
| 90 |
console.log(` [done] todos: ${todos.length} rows in ${Date.now() - t6}ms`);
|
| 91 |
|
| 92 |
+
if (!skipTransaction) db.exec('COMMIT');
|
| 93 |
+
console.log(`[Seed] Seeding done in ${Date.now() - t0}ms`);
|
| 94 |
} catch (error) {
|
| 95 |
+
if (!skipTransaction) db.exec('ROLLBACK');
|
| 96 |
+
console.error('[Seed] Seeding failed:', error.message);
|
| 97 |
throw error;
|
| 98 |
}
|
| 99 |
}
|
| 100 |
+
/* v8 ignore stop */
|
| 101 |
|
| 102 |
/* v8 ignore next 5 */
|
| 103 |
if (require.main === module) {
|
| 104 |
+
seed({ runMigrate: false }).then(() => process.exit(0)).catch((error) => {
|
| 105 |
+
console.error('[Seed] Seeding failed:', error.message);
|
| 106 |
process.exit(1);
|
| 107 |
});
|
| 108 |
}
|
tests/README.md
CHANGED
|
@@ -37,9 +37,10 @@ tests/
|
|
| 37 |
coverage.js # Shared test utilities (save/restore/setEnv/clearCjs)
|
| 38 |
index.js # startServer / stopServer / request utilities
|
| 39 |
seed.js # Standalone script to create & seed temp DB
|
|
|
|
| 40 |
```
|
| 41 |
|
| 42 |
-
**Total:
|
| 43 |
|
| 44 |
## Test design
|
| 45 |
|
|
@@ -61,6 +62,7 @@ Unit tests cover every source module individually. Each module has its own test
|
|
| 61 |
| `server/index.js` (ESM) | `tests/server/coverage-printlog.test.js` | Dynamic `import()` for V8-covered printLog, startServer, 500 catch |
|
| 62 |
| `db/migrate.js` | `tests/db/migrate.test.js` | Real migration + corrupt DB failure path |
|
| 63 |
| `db/seed.js` | `tests/db/seed.test.js` | Dependency injection — `database` and `fetch` injected |
|
|
|
|
| 64 |
| `db/sql-logger.js` | `tests/db/sql-logger.test.js`| Proxy wrapper behavior on exec/prepare/run/get/all |
|
| 65 |
|
| 66 |
### Key testing patterns
|
|
|
|
| 37 |
coverage.js # Shared test utilities (save/restore/setEnv/clearCjs)
|
| 38 |
index.js # startServer / stopServer / request utilities
|
| 39 |
seed.js # Standalone script to create & seed temp DB
|
| 40 |
+
seed-settings-coverage.test.js # Seed-settings.js V8 coverage (2 tests)
|
| 41 |
```
|
| 42 |
|
| 43 |
+
**Total: 145 tests across 12 test files.**
|
| 44 |
|
| 45 |
## Test design
|
| 46 |
|
|
|
|
| 62 |
| `server/index.js` (ESM) | `tests/server/coverage-printlog.test.js` | Dynamic `import()` for V8-covered printLog, startServer, 500 catch |
|
| 63 |
| `db/migrate.js` | `tests/db/migrate.test.js` | Real migration + corrupt DB failure path |
|
| 64 |
| `db/seed.js` | `tests/db/seed.test.js` | Dependency injection — `database` and `fetch` injected |
|
| 65 |
+
| `db/seed-settings.js` | `tests/seed-settings-coverage.test.js` | Real DB + mock DB paths (V8 coverage) |
|
| 66 |
| `db/sql-logger.js` | `tests/db/sql-logger.test.js`| Proxy wrapper behavior on exec/prepare/run/get/all |
|
| 67 |
|
| 68 |
### Key testing patterns
|
tests/db/seed.test.js
CHANGED
|
@@ -25,7 +25,7 @@ vi.mock('../../src/config/index.js', () => configMockFactory())
|
|
| 25 |
|
| 26 |
describe('seed.js', () => {
|
| 27 |
afterEach(() => {
|
| 28 |
-
clearCjs('../../src/db/seed.js', '../../src/db/migrate.js', '../../src/db/index.js'
|
| 29 |
})
|
| 30 |
|
| 31 |
it('imports and migrate runs, seed returns early when DB has data', async () => {
|
|
|
|
| 25 |
|
| 26 |
describe('seed.js', () => {
|
| 27 |
afterEach(() => {
|
| 28 |
+
clearCjs('../../src/db/seed.js', '../../src/db/migrate.js', '../../src/db/index.js')
|
| 29 |
})
|
| 30 |
|
| 31 |
it('imports and migrate runs, seed returns early when DB has data', async () => {
|
tests/helpers/seed.js
CHANGED
|
@@ -13,6 +13,11 @@ migrate();
|
|
| 13 |
|
| 14 |
const db = new DatabaseSync(dbPath);
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
const addr1 = JSON.stringify({ street: '123 Main St', city: 'New York', zipcode: '10001', geo: { lat: '40.7128', lng: '-74.0060' } });
|
| 17 |
const comp1 = JSON.stringify({ name: 'Tech Corp', catchPhrase: 'Innovate the future' });
|
| 18 |
db.prepare('INSERT INTO users (id,name,username,email,phone,website,address,company) VALUES (1,?,?,?,?,?,?,?)')
|
|
@@ -43,5 +48,3 @@ db.prepare('INSERT INTO photos (id,albumId,title,url,thumbnailUrl) VALUES (2,1,?
|
|
| 43 |
db.prepare('INSERT INTO todos (id,userId,title,completed) VALUES (1,1,?,?)').run('Buy groceries', 0);
|
| 44 |
db.prepare('INSERT INTO todos (id,userId,title,completed) VALUES (2,1,?,?)').run('Write tests', 1);
|
| 45 |
db.prepare('INSERT INTO todos (id,userId,title,completed) VALUES (3,2,?,?)').run('Learn vitest', 0);
|
| 46 |
-
|
| 47 |
-
db.close();
|
|
|
|
| 13 |
|
| 14 |
const db = new DatabaseSync(dbPath);
|
| 15 |
|
| 16 |
+
(async () => {
|
| 17 |
+
const { seedSettings } = require('../../src/db/seed-settings');
|
| 18 |
+
await seedSettings({ database: db, runMigrate: false });
|
| 19 |
+
})().then(() => db.close()).catch(() => {});
|
| 20 |
+
|
| 21 |
const addr1 = JSON.stringify({ street: '123 Main St', city: 'New York', zipcode: '10001', geo: { lat: '40.7128', lng: '-74.0060' } });
|
| 22 |
const comp1 = JSON.stringify({ name: 'Tech Corp', catchPhrase: 'Innovate the future' });
|
| 23 |
db.prepare('INSERT INTO users (id,name,username,email,phone,website,address,company) VALUES (1,?,?,?,?,?,?,?)')
|
|
|
|
| 48 |
db.prepare('INSERT INTO todos (id,userId,title,completed) VALUES (1,1,?,?)').run('Buy groceries', 0);
|
| 49 |
db.prepare('INSERT INTO todos (id,userId,title,completed) VALUES (2,1,?,?)').run('Write tests', 1);
|
| 50 |
db.prepare('INSERT INTO todos (id,userId,title,completed) VALUES (3,2,?,?)').run('Learn vitest', 0);
|
|
|
|
|
|
tests/seed-settings-coverage.test.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect, vi, afterAll } from 'vitest'
|
| 2 |
+
import { createRequire } from 'module'
|
| 3 |
+
import { mkdtempSync, rmSync } from 'fs'
|
| 4 |
+
import { tmpdir } from 'os'
|
| 5 |
+
import { join } from 'path'
|
| 6 |
+
|
| 7 |
+
const _require = createRequire(import.meta.url)
|
| 8 |
+
const tmpDir = mkdtempSync(join(tmpdir(), 'ss-cov-'))
|
| 9 |
+
|
| 10 |
+
afterAll(() => {
|
| 11 |
+
try { rmSync(tmpDir, { recursive: true, force: true }) } catch {}
|
| 12 |
+
})
|
| 13 |
+
|
| 14 |
+
describe('seed-settings.js', () => {
|
| 15 |
+
it('calls migrate and seeds env vars when runMigrate is true', async () => {
|
| 16 |
+
const dbPath = join(tmpDir, 'seed-settings.db')
|
| 17 |
+
const origDbPath = process.env.DB_PATH
|
| 18 |
+
process.env.DB_PATH = dbPath
|
| 19 |
+
|
| 20 |
+
const seedSettings = _require('../src/db/seed-settings.js').seedSettings
|
| 21 |
+
const count = await seedSettings()
|
| 22 |
+
|
| 23 |
+
expect(count).toBeTypeOf('number')
|
| 24 |
+
expect(count).toBeGreaterThan(0)
|
| 25 |
+
|
| 26 |
+
const { DatabaseSync } = await import('node:sqlite')
|
| 27 |
+
const db = new DatabaseSync(dbPath)
|
| 28 |
+
const row = db.prepare('SELECT COUNT(*) as c FROM settings').get()
|
| 29 |
+
expect(row.c).toBe(count)
|
| 30 |
+
db.close()
|
| 31 |
+
|
| 32 |
+
const count2 = await seedSettings()
|
| 33 |
+
expect(count2).toBe(0)
|
| 34 |
+
|
| 35 |
+
if (origDbPath) process.env.DB_PATH = origDbPath
|
| 36 |
+
else delete process.env.DB_PATH
|
| 37 |
+
})
|
| 38 |
+
|
| 39 |
+
it('skips migrate when runMigrate is false', async () => {
|
| 40 |
+
const origAdminKey = process.env.ADMIN_KEY
|
| 41 |
+
process.env.ADMIN_KEY = 'test-key'
|
| 42 |
+
|
| 43 |
+
const mockDb = {
|
| 44 |
+
prepare: () => ({ run: vi.fn(), get: vi.fn().mockReturnValue({ rowCount: 0 }) }),
|
| 45 |
+
exec: vi.fn(),
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
const seedSettings = _require('../src/db/seed-settings.js').seedSettings
|
| 49 |
+
const result = await seedSettings({ database: mockDb, runMigrate: false })
|
| 50 |
+
|
| 51 |
+
expect(result).toBeTypeOf('number')
|
| 52 |
+
|
| 53 |
+
if (origAdminKey !== undefined) process.env.ADMIN_KEY = origAdminKey
|
| 54 |
+
else delete process.env.ADMIN_KEY
|
| 55 |
+
})
|
| 56 |
+
})
|