Spaces:
Sleeping
Sleeping
Commit ·
eab7289
1
Parent(s): 45c48e9
feat: add pagination, search, and sorting to list endpoints
Browse files- Support _page, _limit, _start, and _end pagination parameters
- Add q text search across resources
- Add _sort and _order on all listable resources
- .env.example +3 -0
- .env.prod.example +3 -0
- .env.test +3 -0
- README.md +58 -8
- src/config/index.js +2 -0
- src/db/index.js +69 -12
- src/server/index.js +37 -11
- tests/README.md +4 -4
- tests/db/database.test.js +165 -0
- tests/server/integration.test.js +139 -9
.env.example
CHANGED
|
@@ -36,6 +36,9 @@ REDIS_DB=0
|
|
| 36 |
# Request body size limit (bytes, default 1 MB)
|
| 37 |
# MAX_BODY_SIZE=1048576
|
| 38 |
|
|
|
|
|
|
|
|
|
|
| 39 |
# Debug: log all SQL queries to stderr
|
| 40 |
# DEBUG_SQL=true
|
| 41 |
|
|
|
|
| 36 |
# Request body size limit (bytes, default 1 MB)
|
| 37 |
# MAX_BODY_SIZE=1048576
|
| 38 |
|
| 39 |
+
# Default page size for pagination
|
| 40 |
+
# DEFAULT_PAGE_SIZE=10
|
| 41 |
+
|
| 42 |
# Debug: log all SQL queries to stderr
|
| 43 |
# DEBUG_SQL=true
|
| 44 |
|
.env.prod.example
CHANGED
|
@@ -26,6 +26,9 @@
|
|
| 26 |
# Request body size limit (bytes, default 1 MB)
|
| 27 |
# MAX_BODY_SIZE=1048576
|
| 28 |
|
|
|
|
|
|
|
|
|
|
| 29 |
# Debug: log all SQL queries to stderr
|
| 30 |
# DEBUG_SQL=false
|
| 31 |
|
|
|
|
| 26 |
# Request body size limit (bytes, default 1 MB)
|
| 27 |
# MAX_BODY_SIZE=1048576
|
| 28 |
|
| 29 |
+
# Default page size for pagination
|
| 30 |
+
# DEFAULT_PAGE_SIZE=10
|
| 31 |
+
|
| 32 |
# Debug: log all SQL queries to stderr
|
| 33 |
# DEBUG_SQL=false
|
| 34 |
|
.env.test
CHANGED
|
@@ -25,6 +25,9 @@ DB_PATH=./storage/test.db
|
|
| 25 |
# Request body size limit (bytes, default 1 MB)
|
| 26 |
# MAX_BODY_SIZE=1048576
|
| 27 |
|
|
|
|
|
|
|
|
|
|
| 28 |
# Debug: log all SQL queries to stderr
|
| 29 |
DEBUG_SQL=false
|
| 30 |
|
|
|
|
| 25 |
# Request body size limit (bytes, default 1 MB)
|
| 26 |
# MAX_BODY_SIZE=1048576
|
| 27 |
|
| 28 |
+
# Default page size for pagination
|
| 29 |
+
# DEFAULT_PAGE_SIZE=10
|
| 30 |
+
|
| 31 |
# Debug: log all SQL queries to stderr
|
| 32 |
DEBUG_SQL=false
|
| 33 |
|
README.md
CHANGED
|
@@ -53,6 +53,7 @@ Environment files are loaded by `src/config/load-env.js` (auto-run via `src/conf
|
|
| 53 |
| `RATE_LIMIT_WINDOW_MS` | `60000` | Time window in milliseconds (default 1 min) |
|
| 54 |
| `SEED_API_BASE_URL` | `https://jsonplaceholder.typicode.com` | Base URL for seed data API |
|
| 55 |
| `MAX_BODY_SIZE` | `1048576` | Max request body size in bytes (minimum 1) |
|
|
|
|
| 56 |
|
| 57 |
---
|
| 58 |
|
|
@@ -80,7 +81,7 @@ Environment files are loaded by `src/config/load-env.js` (auto-run via `src/conf
|
|
| 80 |
| `PATCH` | `/api/:table/:id` | Partial update |
|
| 81 |
| `DELETE` | `/api/:table/:id` | Delete resource |
|
| 82 |
|
| 83 |
-
### Query String Filtering
|
| 84 |
|
| 85 |
```bash
|
| 86 |
# Filter posts by userId
|
|
@@ -95,6 +96,57 @@ GET /api/comments?postId=1
|
|
| 95 |
|
| 96 |
Filterable columns vary by table (e.g., `title`, `email`, `username`). The `completed` field accepts `true`/`false` strings.
|
| 97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
### System Endpoints
|
| 99 |
|
| 100 |
| Path | Description |
|
|
@@ -182,7 +234,7 @@ json-api-server/
|
|
| 182 |
│ │ ├── config.test.js # Config defaults and env var branches (8)
|
| 183 |
│ │ └── load-env.test.js # Load-env file loading chain and error paths (7)
|
| 184 |
│ ├── db/
|
| 185 |
-
│ │ ├── database.test.js # Database CRUD, pagination, search, sort (
|
| 186 |
│ │ ├── migrate.test.js # Migration success and failure paths (2)
|
| 187 |
│ │ ├── seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5)
|
| 188 |
│ │ └── sql-logger.test.js # SQL query logger wrapping (5)
|
|
@@ -192,7 +244,7 @@ json-api-server/
|
|
| 192 |
│ │ └── redis.test.js # RESP protocol encoding/parsing, constructor options (25)
|
| 193 |
│ ├── server/
|
| 194 |
│ │ ├── coverage-printlog.test.js # V8 coverage: printLog, startServer, 500 catch (3)
|
| 195 |
-
│ │ ├── integration.test.js # API integration tests — real HTTP + SQLite (
|
| 196 |
│ │ └── server.test.js # Server request handler and startup paths (5)
|
| 197 |
│ ├── README.md # Testing documentation
|
| 198 |
│ └── helpers/
|
|
@@ -272,7 +324,7 @@ This runs comprehensive queries to inspect row counts, column metadata, relation
|
|
| 272 |
|
| 273 |
## Testing
|
| 274 |
|
| 275 |
-
Uses **vitest** with **V8 native coverage**. **
|
| 276 |
|
| 277 |
```bash
|
| 278 |
npm test # Run all tests once
|
|
@@ -290,11 +342,9 @@ See [tests/README.md](tests/README.md) for full documentation.
|
|
| 290 |
- **Centralized config** — all environment variables are read in `src/config/index.js` and exported as camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, `dbDebugSql`, etc.) for use across the codebase.
|
| 291 |
- **Lazy rate-limiter config** — `src/middleware/rate-limiter.js` reads config inside `createRateLimiter()` (not at module level), allowing different config values per call and making unit testing straightforward.
|
| 292 |
- **Testable seed script** — `src/db/seed.js` accepts `database` and `fetch` parameters via dependency injection, enabling full unit testing without mocking `require()`.
|
| 293 |
-
|
| 294 |
-
- **SQL query logging** — `src/sql-logger.js` exports `wrapDb`/`wrapStmt` Proxy wrappers that log `exec`, `prepare`, `run`, `get`, and `all` calls to stderr. `src/database.js` uses them via `getWrappedDb()` when `DEBUG_SQL=true`.
|
| 295 |
-
- **Multi-environment** — `src/config.js` requires `src/load-env.js` at module level, which auto-loads dotenv using a priority chain based on `NODE_ENV`. Every consumer (server, migrate, seed) simply requires `config.js` and gets correct env values. In production, dotenv is skipped entirely — env vars must come from the deployment environment.
|
| 296 |
- **Multi-environment** — `src/config/index.js` requires `src/config/load-env.js` at module level, which chain-loads all dotenv files in priority order with `override: false` — existing `process.env` values and earlier files take precedence over later ones. Every consumer (server, migrate, seed) simply requires `src/config/index.js` and gets correct env values. In production, dotenv is skipped entirely — env vars must come from the deployment environment.
|
| 297 |
-
|
| 298 |
- **CORS** enabled on all routes
|
| 299 |
- **Graceful shutdown** — handles `SIGINT` and `SIGTERM` to close the server and Redis connection cleanly
|
| 300 |
|
|
|
|
| 53 |
| `RATE_LIMIT_WINDOW_MS` | `60000` | Time window in milliseconds (default 1 min) |
|
| 54 |
| `SEED_API_BASE_URL` | `https://jsonplaceholder.typicode.com` | Base URL for seed data API |
|
| 55 |
| `MAX_BODY_SIZE` | `1048576` | Max request body size in bytes (minimum 1) |
|
| 56 |
+
| `DEFAULT_PAGE_SIZE` | `10` | Default number of results per page for `_page`/`_limit` pagination |
|
| 57 |
|
| 58 |
---
|
| 59 |
|
|
|
|
| 81 |
| `PATCH` | `/api/:table/:id` | Partial update |
|
| 82 |
| `DELETE` | `/api/:table/:id` | Delete resource |
|
| 83 |
|
| 84 |
+
### Query String Filtering & Pagination
|
| 85 |
|
| 86 |
```bash
|
| 87 |
# Filter posts by userId
|
|
|
|
| 96 |
|
| 97 |
Filterable columns vary by table (e.g., `title`, `email`, `username`). The `completed` field accepts `true`/`false` strings.
|
| 98 |
|
| 99 |
+
### Pagination
|
| 100 |
+
|
| 101 |
+
| Param | Description | Example |
|
| 102 |
+
|-----------|------------------------------------------------|------------------------------|
|
| 103 |
+
| `_page` | Page number (1-based), used with `_limit` | `?_page=1&_limit=10` |
|
| 104 |
+
| `_limit` | Items per page (default: `DEFAULT_PAGE_SIZE`) | `?_page=2&_limit=5` |
|
| 105 |
+
| `_start` | Offset index for slicing | `?_start=10&_end=20` |
|
| 106 |
+
| `_end` | End index (exclusive) for slicing | `?_start=0&_end=5` |
|
| 107 |
+
|
| 108 |
+
### Search
|
| 109 |
+
|
| 110 |
+
Search across text columns using the `q` parameter. Searchable columns vary by table:
|
| 111 |
+
|
| 112 |
+
| Table | Searchable columns |
|
| 113 |
+
|------------|-------------------------------------------|
|
| 114 |
+
| `users` | `name`, `username`, `email` |
|
| 115 |
+
| `posts` | `title`, `body` |
|
| 116 |
+
| `comments` | `name`, `email`, `body` |
|
| 117 |
+
| `albums` | `title` |
|
| 118 |
+
| `photos` | `title` |
|
| 119 |
+
| `todos` | `title` |
|
| 120 |
+
|
| 121 |
+
```bash
|
| 122 |
+
# Search posts by title or body
|
| 123 |
+
GET /api/posts?q=first
|
| 124 |
+
|
| 125 |
+
# Combine search with filter
|
| 126 |
+
GET /api/posts?q=Post&userId=1
|
| 127 |
+
|
| 128 |
+
# Search todos
|
| 129 |
+
GET /api/todos?q=groceries
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
### Sorting
|
| 133 |
+
|
| 134 |
+
| Param | Values | Description |
|
| 135 |
+
|----------|----------------|--------------------------------------|
|
| 136 |
+
| `_sort` | column name | Column to sort by |
|
| 137 |
+
| `_order` | `asc` / `desc` | Sort direction (default: `asc`) |
|
| 138 |
+
|
| 139 |
+
```bash
|
| 140 |
+
# Sort posts by title ascending
|
| 141 |
+
GET /api/posts?_sort=title&_order=asc
|
| 142 |
+
|
| 143 |
+
# Sort posts by title descending
|
| 144 |
+
GET /api/posts?_sort=title&_order=desc
|
| 145 |
+
|
| 146 |
+
# Combine sort with pagination
|
| 147 |
+
GET /api/posts?_sort=id&_order=desc&_limit=2
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
### System Endpoints
|
| 151 |
|
| 152 |
| Path | Description |
|
|
|
|
| 234 |
│ │ ├── config.test.js # Config defaults and env var branches (8)
|
| 235 |
│ │ └── load-env.test.js # Load-env file loading chain and error paths (7)
|
| 236 |
│ ├── db/
|
| 237 |
+
│ │ ├── database.test.js # Database CRUD, pagination, search, sort, SQL injection (9)
|
| 238 |
│ │ ├── migrate.test.js # Migration success and failure paths (2)
|
| 239 |
│ │ ├── seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5)
|
| 240 |
│ │ └── sql-logger.test.js # SQL query logger wrapping (5)
|
|
|
|
| 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 (62)
|
| 248 |
│ │ └── server.test.js # Server request handler and startup paths (5)
|
| 249 |
│ ├── README.md # Testing documentation
|
| 250 |
│ └── helpers/
|
|
|
|
| 324 |
|
| 325 |
## Testing
|
| 326 |
|
| 327 |
+
Uses **vitest** with **V8 native coverage**. **142 tests across 11 test files** cover the full stack — from integration tests (real HTTP server + SQLite) to unit tests for every module.
|
| 328 |
|
| 329 |
```bash
|
| 330 |
npm test # Run all tests once
|
|
|
|
| 342 |
- **Centralized config** — all environment variables are read in `src/config/index.js` and exported as camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, `dbDebugSql`, etc.) for use across the codebase.
|
| 343 |
- **Lazy rate-limiter config** — `src/middleware/rate-limiter.js` reads config inside `createRateLimiter()` (not at module level), allowing different config values per call and making unit testing straightforward.
|
| 344 |
- **Testable seed script** — `src/db/seed.js` accepts `database` and `fetch` parameters via dependency injection, enabling full unit testing without mocking `require()`.
|
| 345 |
+
- **SQL query logging** — `src/db/sql-logger.js` exports `wrapDb`/`wrapStmt` Proxy wrappers that log `exec`, `prepare`, `run`, `get`, and `all` calls to stderr. `src/db/index.js` uses them via `getWrappedDb()` when `DEBUG_SQL=true`.
|
|
|
|
|
|
|
| 346 |
- **Multi-environment** — `src/config/index.js` requires `src/config/load-env.js` at module level, which chain-loads all dotenv files in priority order with `override: false` — existing `process.env` values and earlier files take precedence over later ones. Every consumer (server, migrate, seed) simply requires `src/config/index.js` and gets correct env values. In production, dotenv is skipped entirely — env vars must come from the deployment environment.
|
| 347 |
+
- **SQL injection prevention** — `src/db/index.js` validates `_sort` against a whitelist of known columns and quotes identifiers with `""`; LIKE wildcards (`%`, `_`) are escaped to prevent injection through the `q` parameter
|
| 348 |
- **CORS** enabled on all routes
|
| 349 |
- **Graceful shutdown** — handles `SIGINT` and `SIGTERM` to close the server and Redis connection cleanly
|
| 350 |
|
src/config/index.js
CHANGED
|
@@ -31,6 +31,7 @@ const RATE_LIMIT_WINDOW_SEC = Math.ceil(RATE_LIMIT_WINDOW_MS / 1000);
|
|
| 31 |
const DEFAULT_MAX_BODY_SIZE = 1048576;
|
| 32 |
const parsedMaxBodySize = parseInt(process.env.MAX_BODY_SIZE || String(DEFAULT_MAX_BODY_SIZE), 10);
|
| 33 |
const MAX_BODY_SIZE = isNaN(parsedMaxBodySize) || parsedMaxBodySize < 1 ? DEFAULT_MAX_BODY_SIZE : parsedMaxBodySize;
|
|
|
|
| 34 |
/* v8 ignore stop */
|
| 35 |
|
| 36 |
module.exports = {
|
|
@@ -43,4 +44,5 @@ module.exports = {
|
|
| 43 |
rateLimitWindowMs: RATE_LIMIT_WINDOW_MS,
|
| 44 |
rateLimitWindowSec: RATE_LIMIT_WINDOW_SEC,
|
| 45 |
maxBodySize: MAX_BODY_SIZE,
|
|
|
|
| 46 |
};
|
|
|
|
| 31 |
const DEFAULT_MAX_BODY_SIZE = 1048576;
|
| 32 |
const parsedMaxBodySize = parseInt(process.env.MAX_BODY_SIZE || String(DEFAULT_MAX_BODY_SIZE), 10);
|
| 33 |
const MAX_BODY_SIZE = isNaN(parsedMaxBodySize) || parsedMaxBodySize < 1 ? DEFAULT_MAX_BODY_SIZE : parsedMaxBodySize;
|
| 34 |
+
const DEFAULT_PAGE_SIZE = parseInt(process.env.DEFAULT_PAGE_SIZE || '10', 10);
|
| 35 |
/* v8 ignore stop */
|
| 36 |
|
| 37 |
module.exports = {
|
|
|
|
| 44 |
rateLimitWindowMs: RATE_LIMIT_WINDOW_MS,
|
| 45 |
rateLimitWindowSec: RATE_LIMIT_WINDOW_SEC,
|
| 46 |
maxBodySize: MAX_BODY_SIZE,
|
| 47 |
+
defaultPageSize: DEFAULT_PAGE_SIZE,
|
| 48 |
};
|
src/db/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
'use strict';
|
| 2 |
|
| 3 |
const { DatabaseSync } = require('node:sqlite');
|
| 4 |
-
const { dbPath, dbDebugSql } = require('../config');
|
| 5 |
const { wrapDb } = require('./sql-logger');
|
| 6 |
|
| 7 |
let db;
|
|
@@ -49,27 +49,83 @@ const FILTER_COLS = {
|
|
| 49 |
todos: ['id', 'userId', 'title', 'completed'],
|
| 50 |
};
|
| 51 |
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
const cols = FILTER_COLS[table] || [];
|
| 54 |
const clauses = [];
|
| 55 |
const values = [];
|
| 56 |
|
| 57 |
-
for (const [k, v] of Object.entries(
|
| 58 |
-
|
|
|
|
| 59 |
clauses.push(`${k} = ?`);
|
| 60 |
values.push(k === 'completed' ? (v === 'true' ? 1 : 0) : v);
|
| 61 |
}
|
| 62 |
}
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
}
|
| 68 |
|
| 69 |
function listAll(table, query = {}) {
|
| 70 |
const d = getWrappedDb();
|
| 71 |
-
const {
|
| 72 |
-
const rows = d.prepare(
|
| 73 |
return rows.map((r) => parseRow(table, r));
|
| 74 |
}
|
| 75 |
|
|
@@ -121,7 +177,8 @@ function deleteOne(table, id) {
|
|
| 121 |
function nextId(table) {
|
| 122 |
const d = getWrappedDb();
|
| 123 |
const row = d.prepare(`SELECT MAX(id) as m FROM ${table}`).get();
|
| 124 |
-
|
|
|
|
| 125 |
}
|
| 126 |
|
| 127 |
-
module.exports = { getDb, getWrappedDb, listAll, getOne, insertOne, updateOne, deleteOne, nextId, TABLES };
|
|
|
|
| 1 |
'use strict';
|
| 2 |
|
| 3 |
const { DatabaseSync } = require('node:sqlite');
|
| 4 |
+
const { dbPath, dbDebugSql, defaultPageSize } = require('../config');
|
| 5 |
const { wrapDb } = require('./sql-logger');
|
| 6 |
|
| 7 |
let db;
|
|
|
|
| 49 |
todos: ['id', 'userId', 'title', 'completed'],
|
| 50 |
};
|
| 51 |
|
| 52 |
+
const SEARCH_COLS = {
|
| 53 |
+
users: ['name', 'username', 'email'],
|
| 54 |
+
posts: ['title', 'body'],
|
| 55 |
+
comments: ['name', 'email', 'body'],
|
| 56 |
+
albums: ['title'],
|
| 57 |
+
photos: ['title'],
|
| 58 |
+
todos: ['title'],
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
function buildWhere(table, query = {}) {
|
| 62 |
+
const filters = {};
|
| 63 |
+
let page, limit, start, end, sort, order, search;
|
| 64 |
+
|
| 65 |
+
for (const [k, v] of Object.entries(query)) {
|
| 66 |
+
switch (k) {
|
| 67 |
+
case '_page': page = parseInt(v, 10); break;
|
| 68 |
+
case '_limit': limit = parseInt(v, 10); break;
|
| 69 |
+
case '_start': start = parseInt(v, 10); break;
|
| 70 |
+
case '_end': end = parseInt(v, 10); break;
|
| 71 |
+
case '_sort': sort = v; break;
|
| 72 |
+
case '_order': order = v; break;
|
| 73 |
+
case 'q': search = v; break;
|
| 74 |
+
default: filters[k] = v; break;
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
const cols = FILTER_COLS[table] || [];
|
| 79 |
const clauses = [];
|
| 80 |
const values = [];
|
| 81 |
|
| 82 |
+
for (const [k, v] of Object.entries(filters)) {
|
| 83 |
+
const isKnownCol = cols.includes(k);
|
| 84 |
+
if (isKnownCol) {
|
| 85 |
clauses.push(`${k} = ?`);
|
| 86 |
values.push(k === 'completed' ? (v === 'true' ? 1 : 0) : v);
|
| 87 |
}
|
| 88 |
}
|
| 89 |
+
|
| 90 |
+
const searchCols = SEARCH_COLS[table] || [];
|
| 91 |
+
if (search && searchCols.length > 0) {
|
| 92 |
+
const escaped = search.replace(/[%_\\]/g, '\\$&');
|
| 93 |
+
const searchClauses = searchCols.map((c) => `${c} LIKE ? ESCAPE '\\'`);
|
| 94 |
+
const likeVal = `%${escaped}%`;
|
| 95 |
+
clauses.push(`(${searchClauses.join(' OR ')})`);
|
| 96 |
+
for (const _ of searchCols) values.push(likeVal);
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
const hasClauses = clauses.length > 0;
|
| 100 |
+
let sql = `SELECT * FROM ${table}`;
|
| 101 |
+
if (hasClauses) {
|
| 102 |
+
sql += ' WHERE ' + clauses.join(' AND ');
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
const allCols = [...new Set([...cols, ...searchCols])];
|
| 106 |
+
const safeSort = sort && allCols.includes(sort) ? sort : null;
|
| 107 |
+
if (safeSort) {
|
| 108 |
+
const dir = order && ['asc', 'desc'].includes(order.toLowerCase()) ? order.toUpperCase() : 'ASC';
|
| 109 |
+
sql += ` ORDER BY "${safeSort}" ${dir}`;
|
| 110 |
+
}
|
| 111 |
+
const hasPage = page !== undefined;
|
| 112 |
+
const hasLimit = limit !== undefined;
|
| 113 |
+
if (start !== undefined) {
|
| 114 |
+
const lim = end !== undefined ? end - start : -1;
|
| 115 |
+
sql += ` LIMIT ${lim} OFFSET ${start}`;
|
| 116 |
+
} else if (hasPage || hasLimit) {
|
| 117 |
+
const p = hasPage ? page : 1;
|
| 118 |
+
const lim = hasLimit ? limit : defaultPageSize;
|
| 119 |
+
sql += ` LIMIT ${lim} OFFSET ${(p - 1) * lim}`;
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
return { sql, values };
|
| 123 |
}
|
| 124 |
|
| 125 |
function listAll(table, query = {}) {
|
| 126 |
const d = getWrappedDb();
|
| 127 |
+
const { sql, values } = buildWhere(table, query);
|
| 128 |
+
const rows = d.prepare(sql).all(...values);
|
| 129 |
return rows.map((r) => parseRow(table, r));
|
| 130 |
}
|
| 131 |
|
|
|
|
| 177 |
function nextId(table) {
|
| 178 |
const d = getWrappedDb();
|
| 179 |
const row = d.prepare(`SELECT MAX(id) as m FROM ${table}`).get();
|
| 180 |
+
const m = row.m ?? 0;
|
| 181 |
+
return m + 1;
|
| 182 |
}
|
| 183 |
|
| 184 |
+
module.exports = { getDb, getWrappedDb, buildWhere, listAll, getOne, insertOne, updateOne, deleteOne, nextId, TABLES };
|
src/server/index.js
CHANGED
|
@@ -59,7 +59,10 @@ function readBody(req, res) {
|
|
| 59 |
});
|
| 60 |
req.on('end', () => {
|
| 61 |
try {
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
| 63 |
} catch (_) {
|
| 64 |
reject(new Error('Invalid JSON'));
|
| 65 |
}
|
|
@@ -68,6 +71,15 @@ function readBody(req, res) {
|
|
| 68 |
});
|
| 69 |
}
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
function parseRoute(pathname) {
|
| 72 |
const parts = pathname.replace(/^\/+|\/+$/g, '').split('/');
|
| 73 |
/* v8 ignore next */
|
|
@@ -78,7 +90,7 @@ function parseRoute(pathname) {
|
|
| 78 |
|
| 79 |
if (!db.TABLES.includes(table)) return null;
|
| 80 |
/* v8 ignore next */
|
| 81 |
-
if (rawId && isNaN(id)) return
|
| 82 |
|
| 83 |
return { table, id, sub };
|
| 84 |
}
|
|
@@ -92,6 +104,22 @@ const NESTED = {
|
|
| 92 |
async function handleGET(req, res, route, query) {
|
| 93 |
const { table, id, sub } = route;
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
if (id !== null && sub) {
|
| 96 |
const parentExists = db.getOne(table, id);
|
| 97 |
if (!parentExists) return notFound(res);
|
|
@@ -115,9 +143,8 @@ async function handleGET(req, res, route, query) {
|
|
| 115 |
|
| 116 |
async function handlePOST(req, res, route) {
|
| 117 |
const { table } = route;
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
catch (e) { if (e !== BODY_TOO_LARGE) return badRequest(res, 'Invalid JSON body'); return json(res, 413, { error: 'Request body too large' }); }
|
| 121 |
|
| 122 |
if (!body.id) body.id = db.nextId(table);
|
| 123 |
|
|
@@ -133,9 +160,8 @@ async function handlePUT(req, res, route) {
|
|
| 133 |
const { table, id } = route;
|
| 134 |
if (id === null) return badRequest(res, 'PUT requires an id');
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
catch (e) { if (e !== BODY_TOO_LARGE) return badRequest(res, 'Invalid JSON body'); return json(res, 413, { error: 'Request body too large' }); }
|
| 139 |
|
| 140 |
const updated = db.updateOne(table, id, body, true);
|
| 141 |
updated ? json(res, 200, updated) : notFound(res);
|
|
@@ -145,9 +171,8 @@ async function handlePATCH(req, res, route) {
|
|
| 145 |
const { table, id } = route;
|
| 146 |
if (id === null) return badRequest(res, 'PATCH requires an id');
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
catch (e) { if (e !== BODY_TOO_LARGE) return badRequest(res, 'Invalid JSON body'); return json(res, 413, { error: 'Request body too large' }); }
|
| 151 |
|
| 152 |
const updated = db.updateOne(table, id, body, false);
|
| 153 |
updated ? json(res, 200, updated) : notFound(res);
|
|
@@ -211,6 +236,7 @@ async function requestHandler(req, res) {
|
|
| 211 |
|
| 212 |
const route = parseRoute(pathname);
|
| 213 |
if (!route) return notFound(res, `Unknown route: ${pathname}`);
|
|
|
|
| 214 |
|
| 215 |
try {
|
| 216 |
switch (method) {
|
|
|
|
| 59 |
});
|
| 60 |
req.on('end', () => {
|
| 61 |
try {
|
| 62 |
+
let parsed = body ? JSON.parse(body) : {};
|
| 63 |
+
/* v8 ignore next 2 — defensive: JSON.parse can return null */
|
| 64 |
+
if (parsed === null) parsed = {};
|
| 65 |
+
resolve(parsed);
|
| 66 |
} catch (_) {
|
| 67 |
reject(new Error('Invalid JSON'));
|
| 68 |
}
|
|
|
|
| 71 |
});
|
| 72 |
}
|
| 73 |
|
| 74 |
+
async function readBodySafe(req, res) {
|
| 75 |
+
try {
|
| 76 |
+
return await readBody(req, res);
|
| 77 |
+
} catch (e) {
|
| 78 |
+
if (e !== BODY_TOO_LARGE) badRequest(res, 'Invalid JSON body');
|
| 79 |
+
}
|
| 80 |
+
return null;
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
function parseRoute(pathname) {
|
| 84 |
const parts = pathname.replace(/^\/+|\/+$/g, '').split('/');
|
| 85 |
/* v8 ignore next */
|
|
|
|
| 90 |
|
| 91 |
if (!db.TABLES.includes(table)) return null;
|
| 92 |
/* v8 ignore next */
|
| 93 |
+
if (rawId && isNaN(id)) return { invalidId: true };
|
| 94 |
|
| 95 |
return { table, id, sub };
|
| 96 |
}
|
|
|
|
| 104 |
async function handleGET(req, res, route, query) {
|
| 105 |
const { table, id, sub } = route;
|
| 106 |
|
| 107 |
+
for (const param of ['_page', '_limit', '_start', '_end']) {
|
| 108 |
+
if (query[param] !== undefined) {
|
| 109 |
+
if (query[param] === '') {
|
| 110 |
+
delete query[param];
|
| 111 |
+
} else {
|
| 112 |
+
const val = Number(query[param]);
|
| 113 |
+
if (!Number.isInteger(val) || val < 0) {
|
| 114 |
+
return badRequest(res, `Invalid ${param}: must be a non-negative integer`);
|
| 115 |
+
}
|
| 116 |
+
if ((param === '_page' || param === '_limit') && val < 1) {
|
| 117 |
+
return badRequest(res, `Invalid ${param}: must be a positive integer`);
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
if (id !== null && sub) {
|
| 124 |
const parentExists = db.getOne(table, id);
|
| 125 |
if (!parentExists) return notFound(res);
|
|
|
|
| 143 |
|
| 144 |
async function handlePOST(req, res, route) {
|
| 145 |
const { table } = route;
|
| 146 |
+
const body = await readBodySafe(req, res);
|
| 147 |
+
if (body === null) return;
|
|
|
|
| 148 |
|
| 149 |
if (!body.id) body.id = db.nextId(table);
|
| 150 |
|
|
|
|
| 160 |
const { table, id } = route;
|
| 161 |
if (id === null) return badRequest(res, 'PUT requires an id');
|
| 162 |
|
| 163 |
+
const body = await readBodySafe(req, res);
|
| 164 |
+
if (body === null) return;
|
|
|
|
| 165 |
|
| 166 |
const updated = db.updateOne(table, id, body, true);
|
| 167 |
updated ? json(res, 200, updated) : notFound(res);
|
|
|
|
| 171 |
const { table, id } = route;
|
| 172 |
if (id === null) return badRequest(res, 'PATCH requires an id');
|
| 173 |
|
| 174 |
+
const body = await readBodySafe(req, res);
|
| 175 |
+
if (body === null) return;
|
|
|
|
| 176 |
|
| 177 |
const updated = db.updateOne(table, id, body, false);
|
| 178 |
updated ? json(res, 200, updated) : notFound(res);
|
|
|
|
| 236 |
|
| 237 |
const route = parseRoute(pathname);
|
| 238 |
if (!route) return notFound(res, `Unknown route: ${pathname}`);
|
| 239 |
+
if (route.invalidId) return badRequest(res, 'Invalid ID format');
|
| 240 |
|
| 241 |
try {
|
| 242 |
switch (method) {
|
tests/README.md
CHANGED
|
@@ -21,7 +21,7 @@ tests/
|
|
| 21 |
config.test.js # Config defaults and env var branches (8 tests)
|
| 22 |
load-env.test.js # Load-env file loading chain and error paths (7 tests)
|
| 23 |
db/
|
| 24 |
-
database.test.js # Database CRUD, pagination, search, sort (
|
| 25 |
migrate.test.js # Migration success and failure paths (2 tests)
|
| 26 |
seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5 tests)
|
| 27 |
sql-logger.test.js # SQL query logger wrapping tests (5 tests)
|
|
@@ -31,7 +31,7 @@ tests/
|
|
| 31 |
redis.test.js # RESP protocol encoding/parsing, constructor options (25 tests)
|
| 32 |
server/
|
| 33 |
coverage-printlog.test.js # V8 coverage: printLog, startServer, 500 catch (3 tests)
|
| 34 |
-
integration.test.js # API integration tests — real HTTP + SQLite (
|
| 35 |
server.test.js # Server request handler and startup paths (5 tests)
|
| 36 |
helpers/
|
| 37 |
coverage.js # Shared test utilities (save/restore/setEnv/clearCjs)
|
|
@@ -39,13 +39,13 @@ tests/
|
|
| 39 |
seed.js # Standalone script to create & seed temp DB
|
| 40 |
```
|
| 41 |
|
| 42 |
-
**Total:
|
| 43 |
|
| 44 |
## Test design
|
| 45 |
|
| 46 |
### Integration tests (`tests/server/integration.test.js`)
|
| 47 |
|
| 48 |
-
Each run creates an isolated temp SQLite database, seeds it with test data via a child process (`helpers/seed.js`), then starts the server on port 3199. Tests make real HTTP requests and validate the full request lifecycle. Rate limiting is disabled via `RATE_LIMIT_ENABLED=false` in the test helper. The temp directory is cleaned up after all tests finish.
|
| 49 |
|
| 50 |
### Unit tests (`tests/config/`, `tests/db/`, `tests/middleware/`, `tests/redis/`, `tests/server/`)
|
| 51 |
|
|
|
|
| 21 |
config.test.js # Config defaults and env var branches (8 tests)
|
| 22 |
load-env.test.js # Load-env file loading chain and error paths (7 tests)
|
| 23 |
db/
|
| 24 |
+
database.test.js # Database CRUD, pagination, search, sort, SQL injection (10 tests)
|
| 25 |
migrate.test.js # Migration success and failure paths (2 tests)
|
| 26 |
seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5 tests)
|
| 27 |
sql-logger.test.js # SQL query logger wrapping tests (5 tests)
|
|
|
|
| 31 |
redis.test.js # RESP protocol encoding/parsing, constructor options (25 tests)
|
| 32 |
server/
|
| 33 |
coverage-printlog.test.js # V8 coverage: printLog, startServer, 500 catch (3 tests)
|
| 34 |
+
integration.test.js # API integration tests — real HTTP + SQLite (67 tests)
|
| 35 |
server.test.js # Server request handler and startup paths (5 tests)
|
| 36 |
helpers/
|
| 37 |
coverage.js # Shared test utilities (save/restore/setEnv/clearCjs)
|
|
|
|
| 39 |
seed.js # Standalone script to create & seed temp DB
|
| 40 |
```
|
| 41 |
|
| 42 |
+
**Total: 143 tests across 11 test files.**
|
| 43 |
|
| 44 |
## Test design
|
| 45 |
|
| 46 |
### Integration tests (`tests/server/integration.test.js`)
|
| 47 |
|
| 48 |
+
Each run creates an isolated temp SQLite database, seeds it with test data via a child process (`helpers/seed.js`), then starts the server on port 3199. Tests make real HTTP requests and validate the full request lifecycle — including pagination (`_page`/`_limit`/`_start`/`_end`), search (`q`), sorting (`_sort`/`_order`), and CRUD operations. Rate limiting is disabled via `RATE_LIMIT_ENABLED=false` in the test helper. The temp directory is cleaned up after all tests finish.
|
| 49 |
|
| 50 |
### Unit tests (`tests/config/`, `tests/db/`, `tests/middleware/`, `tests/redis/`, `tests/server/`)
|
| 51 |
|
tests/db/database.test.js
CHANGED
|
@@ -103,6 +103,25 @@ describe('database.js', () => {
|
|
| 103 |
expect(pending).toHaveLength(1)
|
| 104 |
expect(pending[0].completed).toBe(false)
|
| 105 |
expect(mod.getOne('users', 999)).toBeNull()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
restore(s)
|
| 107 |
})
|
| 108 |
|
|
@@ -167,4 +186,150 @@ describe('database.js', () => {
|
|
| 167 |
expect(mod.deleteOne('todos', 1).id).toBe(1)
|
| 168 |
restore(s)
|
| 169 |
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
})
|
|
|
|
| 103 |
expect(pending).toHaveLength(1)
|
| 104 |
expect(pending[0].completed).toBe(false)
|
| 105 |
expect(mod.getOne('users', 999)).toBeNull()
|
| 106 |
+
|
| 107 |
+
const startEnd = mod.listAll('users', { _start: '0', _end: '2' })
|
| 108 |
+
expect(startEnd).toHaveLength(2)
|
| 109 |
+
expect(startEnd[0].id).toBe(1)
|
| 110 |
+
expect(startEnd[1].id).toBe(2)
|
| 111 |
+
|
| 112 |
+
const pageLimit = mod.listAll('users', { _page: '1', _limit: '1' })
|
| 113 |
+
expect(pageLimit).toHaveLength(1)
|
| 114 |
+
expect(pageLimit[0].id).toBe(1)
|
| 115 |
+
|
| 116 |
+
db.exec('CREATE TABLE extras (id INTEGER PRIMARY KEY, label TEXT)')
|
| 117 |
+
db.prepare('INSERT INTO extras (id, label) VALUES (?, ?)').run(1, 'Hello')
|
| 118 |
+
const unknown = mod.listAll('extras', { label: 'Hello' })
|
| 119 |
+
expect(unknown).toHaveLength(1)
|
| 120 |
+
expect(unknown[0].id).toBe(1)
|
| 121 |
+
|
| 122 |
+
const searchIgnored = mod.listAll('extras', { q: 'Hello' })
|
| 123 |
+
expect(searchIgnored).toHaveLength(1)
|
| 124 |
+
|
| 125 |
restore(s)
|
| 126 |
})
|
| 127 |
|
|
|
|
| 186 |
expect(mod.deleteOne('todos', 1).id).toBe(1)
|
| 187 |
restore(s)
|
| 188 |
})
|
| 189 |
+
|
| 190 |
+
it('covers listAll params via direct require for V8 coverage accuracy', () => {
|
| 191 |
+
const dbPath = path.join(tmpDir, 'db-params.db')
|
| 192 |
+
const s = save('DB_PATH', 'DEBUG_SQL')
|
| 193 |
+
process.env.DB_PATH = dbPath
|
| 194 |
+
process.env.DEBUG_SQL = 'false'
|
| 195 |
+
clearCjs('../../src/db/index.js', '../../src/config/index.js')
|
| 196 |
+
const mod = _require('../../src/db/index.js')
|
| 197 |
+
const db = mod.getDb()
|
| 198 |
+
db.exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT, username TEXT, phone TEXT, website TEXT)')
|
| 199 |
+
db.prepare('INSERT INTO users (id, name, email, username, phone, website) VALUES (?, ?, ?, ?, ?, ?)').run(1, 'Alice', 'alice@test.com', 'alice', '123', 'alice.dev')
|
| 200 |
+
db.prepare('INSERT INTO users (id, name, email, username, phone, website) VALUES (?, ?, ?, ?, ?, ?)').run(2, 'Bob', 'bob@test.com', 'bob', '456', 'bob.dev')
|
| 201 |
+
db.prepare('INSERT INTO users (id, name, email, username, phone, website) VALUES (?, ?, ?, ?, ?, ?)').run(3, 'Charlie', 'charlie@test.com', 'charlie', '789', 'charlie.dev')
|
| 202 |
+
db.exec('CREATE TABLE todos (id INTEGER PRIMARY KEY, userId INTEGER, title TEXT, completed INTEGER)')
|
| 203 |
+
db.prepare('INSERT INTO todos (id, userId, title, completed) VALUES (?, ?, ?, ?)').run(1, 1, 'Done', 1)
|
| 204 |
+
db.prepare('INSERT INTO todos (id, userId, title, completed) VALUES (?, ?, ?, ?)').run(2, 1, 'Todo', 0)
|
| 205 |
+
db.exec('CREATE TABLE extras (id INTEGER PRIMARY KEY, label TEXT)')
|
| 206 |
+
db.prepare('INSERT INTO extras (id, label) VALUES (?, ?)').run(1, 'Hello')
|
| 207 |
+
|
| 208 |
+
expect(mod.listAll('users', { name: 'Alice', ignored: 'value' })).toHaveLength(1)
|
| 209 |
+
expect(mod.listAll('users', { _start: '0', _end: '2' })).toHaveLength(2)
|
| 210 |
+
expect(mod.listAll('users', { _start: '0' })).toHaveLength(3)
|
| 211 |
+
expect(mod.listAll('users', { _page: '1', _limit: '2' })).toHaveLength(2)
|
| 212 |
+
expect(mod.listAll('users', { _page: '1' })).toHaveLength(3)
|
| 213 |
+
expect(mod.listAll('users', { _limit: '2' })).toHaveLength(2)
|
| 214 |
+
expect(mod.listAll('users', { _sort: 'name', _order: 'desc' })).toHaveLength(3)
|
| 215 |
+
expect(mod.listAll('users', { _sort: 'name', _order: 'asc' })).toHaveLength(3)
|
| 216 |
+
expect(mod.listAll('users', { _sort: 'name' })).toHaveLength(3)
|
| 217 |
+
expect(mod.listAll('users', { _sort: 'nonexistent' })).toHaveLength(3)
|
| 218 |
+
expect(mod.listAll('users', { q: 'Alice' })).toHaveLength(1)
|
| 219 |
+
expect(mod.listAll('todos', { completed: 'true' })).toHaveLength(1)
|
| 220 |
+
expect(mod.listAll('todos', { completed: 'false' })).toHaveLength(1)
|
| 221 |
+
expect(mod.listAll('extras', { label: 'Hello' })).toHaveLength(1)
|
| 222 |
+
expect(mod.listAll('extras', { q: 'Hello' })).toHaveLength(1)
|
| 223 |
+
|
| 224 |
+
restore(s)
|
| 225 |
+
})
|
| 226 |
+
|
| 227 |
+
it('escapes LIKE wildcards to prevent SQL injection', () => {
|
| 228 |
+
const dbPath = path.join(tmpDir, 'db-like.db')
|
| 229 |
+
const s = save('DB_PATH', 'DEBUG_SQL')
|
| 230 |
+
setEnv({ DB_PATH: dbPath, DEBUG_SQL: 'true' })
|
| 231 |
+
clearCjs('../../src/db/index.js', '../../src/config/index.js')
|
| 232 |
+
const mod = _require('../../src/db/index.js')
|
| 233 |
+
const db = mod.getDb()
|
| 234 |
+
db.exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, username TEXT, email TEXT)')
|
| 235 |
+
db.prepare('INSERT INTO users (id, name, username, email) VALUES (?, ?, ?, ?)').run(1, 'task_99%_done', 'userA', 'a@b.com')
|
| 236 |
+
db.prepare('INSERT INTO users (id, name, username, email) VALUES (?, ?, ?, ?)').run(2, 'normal_task', 'userB', 'c@d.com')
|
| 237 |
+
db.prepare('INSERT INTO users (id, name, username, email) VALUES (?, ?, ?, ?)').run(3, 'plain', 'userC', 'e@f.com')
|
| 238 |
+
|
| 239 |
+
const literalPercent = mod.listAll('users', { q: '99%' })
|
| 240 |
+
expect(literalPercent).toHaveLength(1)
|
| 241 |
+
expect(literalPercent[0].name).toBe('task_99%_done')
|
| 242 |
+
|
| 243 |
+
const literalUs = mod.listAll('users', { q: 'task_' })
|
| 244 |
+
expect(literalUs).toHaveLength(1)
|
| 245 |
+
expect(literalUs[0].name).toBe('task_99%_done')
|
| 246 |
+
|
| 247 |
+
const normalSearch = mod.listAll('users', { q: 'normal' })
|
| 248 |
+
expect(normalSearch).toHaveLength(1)
|
| 249 |
+
expect(normalSearch[0].name).toBe('normal_task')
|
| 250 |
+
|
| 251 |
+
restore(s)
|
| 252 |
+
})
|
| 253 |
+
|
| 254 |
+
it('rejects invalid ORDER BY values and quotes identifiers', () => {
|
| 255 |
+
const dbPath = path.join(tmpDir, 'db-sort.db')
|
| 256 |
+
const s = save('DB_PATH', 'DEBUG_SQL')
|
| 257 |
+
setEnv({ DB_PATH: dbPath, DEBUG_SQL: 'false' })
|
| 258 |
+
clearCjs('../../src/db/index.js', '../../src/config/index.js')
|
| 259 |
+
const mod = _require('../../src/db/index.js')
|
| 260 |
+
const db = mod.getDb()
|
| 261 |
+
db.exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)')
|
| 262 |
+
db.prepare('INSERT INTO users (id, name, email) VALUES (?, ?, ?)').run(1, 'Charlie', 'c@t.com')
|
| 263 |
+
db.prepare('INSERT INTO users (id, name, email) VALUES (?, ?, ?)').run(2, 'Alice', 'a@t.com')
|
| 264 |
+
db.prepare('INSERT INTO users (id, name, email) VALUES (?, ?, ?)').run(3, 'Bob', 'b@t.com')
|
| 265 |
+
|
| 266 |
+
const injection = mod.listAll('users', { _sort: 'name; DROP TABLE users--', _order: 'asc' })
|
| 267 |
+
expect(injection).toHaveLength(3)
|
| 268 |
+
|
| 269 |
+
const sorted = mod.listAll('users', { _sort: 'name', _order: 'asc' })
|
| 270 |
+
expect(sorted[0].name).toBe('Alice')
|
| 271 |
+
expect(sorted[1].name).toBe('Bob')
|
| 272 |
+
expect(sorted[2].name).toBe('Charlie')
|
| 273 |
+
|
| 274 |
+
const desc = mod.listAll('users', { _sort: 'name', _order: 'desc' })
|
| 275 |
+
expect(desc[0].name).toBe('Charlie')
|
| 276 |
+
expect(desc[2].name).toBe('Alice')
|
| 277 |
+
|
| 278 |
+
restore(s)
|
| 279 |
+
})
|
| 280 |
+
|
| 281 |
+
it('covers search via q parameter', () => {
|
| 282 |
+
const dbPath = path.join(tmpDir, 'db-search.db')
|
| 283 |
+
const s = save('DB_PATH', 'DEBUG_SQL')
|
| 284 |
+
setEnv({ DB_PATH: dbPath, DEBUG_SQL: 'true' })
|
| 285 |
+
clearCjs('../../src/db/index.js', '../../src/config/index.js')
|
| 286 |
+
const mod = _require('../../src/db/index.js')
|
| 287 |
+
const db = mod.getDb()
|
| 288 |
+
db.exec('CREATE TABLE todos (id INTEGER PRIMARY KEY, userId INTEGER, title TEXT, completed INTEGER)')
|
| 289 |
+
db.prepare('INSERT INTO todos (id, userId, title, completed) VALUES (?, ?, ?, ?)').run(1, 1, 'Buy milk', 0)
|
| 290 |
+
db.prepare('INSERT INTO todos (id, userId, title, completed) VALUES (?, ?, ?, ?)').run(2, 2, 'Buy eggs', 0)
|
| 291 |
+
db.prepare('INSERT INTO todos (id, userId, title, completed) VALUES (?, ?, ?, ?)').run(3, 1, 'Wash car', 1)
|
| 292 |
+
|
| 293 |
+
const results = mod.listAll('todos', { q: 'Buy', _sort: 'id', _order: 'asc' })
|
| 294 |
+
expect(results).toHaveLength(2)
|
| 295 |
+
|
| 296 |
+
const noResults = mod.listAll('todos', { q: 'Nonexistent' })
|
| 297 |
+
expect(noResults).toHaveLength(0)
|
| 298 |
+
|
| 299 |
+
restore(s)
|
| 300 |
+
})
|
| 301 |
+
|
| 302 |
+
it('buildWhere parses query params into SQL and values', () => {
|
| 303 |
+
const dbPath = path.join(tmpDir, 'db-buildwhere.db')
|
| 304 |
+
const s = save('DB_PATH', 'DEBUG_SQL')
|
| 305 |
+
setEnv({ DB_PATH: dbPath, DEBUG_SQL: 'false' })
|
| 306 |
+
clearCjs('../../src/db/index.js', '../../src/config/index.js')
|
| 307 |
+
const mod = _require('../../src/db/index.js')
|
| 308 |
+
|
| 309 |
+
const res1 = mod.buildWhere('users', { name: 'Alice', _page: '1', _limit: '10' })
|
| 310 |
+
expect(res1.sql).toMatch(/WHERE name = \?/)
|
| 311 |
+
expect(res1.sql).toMatch(/LIMIT 10 OFFSET 0/)
|
| 312 |
+
expect(res1.values).toEqual(['Alice'])
|
| 313 |
+
|
| 314 |
+
const res2 = mod.buildWhere('todos', { completed: 'true' })
|
| 315 |
+
expect(res2.values).toEqual([1])
|
| 316 |
+
expect(res2.sql).toMatch(/WHERE completed = \?/)
|
| 317 |
+
|
| 318 |
+
const res3 = mod.buildWhere('users', { q: 'test', _sort: 'name', _order: 'desc' })
|
| 319 |
+
expect(res3.sql).toContain('LIKE')
|
| 320 |
+
expect(res3.sql).toContain('ORDER BY')
|
| 321 |
+
expect(res3.sql).toContain('DESC')
|
| 322 |
+
|
| 323 |
+
const res4 = mod.buildWhere('users', {})
|
| 324 |
+
expect(res4.sql).toBe('SELECT * FROM users')
|
| 325 |
+
expect(res4.values).toEqual([])
|
| 326 |
+
|
| 327 |
+
const res5 = mod.buildWhere('users', { _start: '0', _end: '5' })
|
| 328 |
+
expect(res5.sql).toMatch(/LIMIT 5 OFFSET 0/)
|
| 329 |
+
|
| 330 |
+
const res6 = mod.buildWhere('nonexistent', { q: 'test' })
|
| 331 |
+
expect(res6.values).toEqual([])
|
| 332 |
+
|
| 333 |
+
restore(s)
|
| 334 |
+
})
|
| 335 |
})
|
tests/server/integration.test.js
CHANGED
|
@@ -143,6 +143,14 @@ describe('404 handling', () => {
|
|
| 143 |
});
|
| 144 |
});
|
| 145 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
describe('Filtering', () => {
|
| 147 |
it('GET /api/todos?userId=1 filters by userId', async () => {
|
| 148 |
const res = await request('/api/todos?userId=1');
|
|
@@ -270,14 +278,6 @@ describe('POST — Create', () => {
|
|
| 270 |
expect(res.status).toBe(400);
|
| 271 |
expect(res.body.error).toBe('Invalid JSON body');
|
| 272 |
});
|
| 273 |
-
|
| 274 |
-
it('POST with unknown column returns 400 from db error', async () => {
|
| 275 |
-
const res = await request('/api/users', {
|
| 276 |
-
method: 'POST',
|
| 277 |
-
body: { name: 'test', extra_col: 'value' },
|
| 278 |
-
});
|
| 279 |
-
expect(res.status).toBe(400);
|
| 280 |
-
});
|
| 281 |
});
|
| 282 |
|
| 283 |
describe('PATCH — Partial update', () => {
|
|
@@ -377,4 +377,134 @@ describe('CORS headers on error responses', () => {
|
|
| 377 |
expect(res.status).toBe(404);
|
| 378 |
expect(res.headers['access-control-allow-origin']).toBe('*');
|
| 379 |
});
|
| 380 |
-
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
});
|
| 144 |
});
|
| 145 |
|
| 146 |
+
describe('400 handling', () => {
|
| 147 |
+
it('GET /api/users/abc returns 400 for invalid ID format', async () => {
|
| 148 |
+
const res = await request('/api/users/abc');
|
| 149 |
+
expect(res.status).toBe(400);
|
| 150 |
+
expect(res.body.error).toBe('Invalid ID format');
|
| 151 |
+
});
|
| 152 |
+
});
|
| 153 |
+
|
| 154 |
describe('Filtering', () => {
|
| 155 |
it('GET /api/todos?userId=1 filters by userId', async () => {
|
| 156 |
const res = await request('/api/todos?userId=1');
|
|
|
|
| 278 |
expect(res.status).toBe(400);
|
| 279 |
expect(res.body.error).toBe('Invalid JSON body');
|
| 280 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
});
|
| 282 |
|
| 283 |
describe('PATCH — Partial update', () => {
|
|
|
|
| 377 |
expect(res.status).toBe(404);
|
| 378 |
expect(res.headers['access-control-allow-origin']).toBe('*');
|
| 379 |
});
|
| 380 |
+
});
|
| 381 |
+
|
| 382 |
+
describe('Pagination', () => {
|
| 383 |
+
it('GET /api/posts?_page=1&_limit=2 returns first page', async () => {
|
| 384 |
+
const res = await request('/api/posts?_page=1&_limit=2');
|
| 385 |
+
expect(res.status).toBe(200);
|
| 386 |
+
expect(res.body.length).toBe(2);
|
| 387 |
+
expect(res.body[0].id).toBe(1);
|
| 388 |
+
expect(res.body[1].id).toBe(2);
|
| 389 |
+
});
|
| 390 |
+
|
| 391 |
+
it('GET /api/posts?_page=2&_limit=2 returns second page', async () => {
|
| 392 |
+
const res = await request('/api/posts?_page=2&_limit=2');
|
| 393 |
+
expect(res.status).toBe(200);
|
| 394 |
+
expect(res.body.length).toBe(2);
|
| 395 |
+
expect(res.body[0].id).toBe(4);
|
| 396 |
+
expect(res.body[1].id).toBe(100);
|
| 397 |
+
});
|
| 398 |
+
|
| 399 |
+
it('GET /api/posts?_start=1&_end=3 returns sliced results', async () => {
|
| 400 |
+
const res = await request('/api/posts?_start=1&_end=3');
|
| 401 |
+
expect(res.status).toBe(200);
|
| 402 |
+
expect(res.body.length).toBe(2);
|
| 403 |
+
expect(res.body[0].id).toBe(2);
|
| 404 |
+
expect(res.body[1].id).toBe(4);
|
| 405 |
+
});
|
| 406 |
+
|
| 407 |
+
it('GET /api/todos?_start=1 returns all from offset', async () => {
|
| 408 |
+
const res = await request('/api/todos?_start=1');
|
| 409 |
+
expect(res.status).toBe(200);
|
| 410 |
+
expect(res.body.length).toBe(2);
|
| 411 |
+
});
|
| 412 |
+
|
| 413 |
+
it('GET /api/posts?_limit=1 limits results', async () => {
|
| 414 |
+
const res = await request('/api/posts?_limit=1');
|
| 415 |
+
expect(res.status).toBe(200);
|
| 416 |
+
expect(res.body.length).toBe(1);
|
| 417 |
+
});
|
| 418 |
+
|
| 419 |
+
it('GET /api/posts?_page=0 returns 400', async () => {
|
| 420 |
+
const res = await request('/api/posts?_page=0');
|
| 421 |
+
expect(res.status).toBe(400);
|
| 422 |
+
expect(res.body.error).toBe('Invalid _page: must be a positive integer');
|
| 423 |
+
});
|
| 424 |
+
|
| 425 |
+
it('GET /api/posts?_page=-1 returns 400', async () => {
|
| 426 |
+
const res = await request('/api/posts?_page=-1');
|
| 427 |
+
expect(res.status).toBe(400);
|
| 428 |
+
expect(res.body.error).toBe('Invalid _page: must be a non-negative integer');
|
| 429 |
+
});
|
| 430 |
+
|
| 431 |
+
it('GET /api/posts?_limit=0 returns 400', async () => {
|
| 432 |
+
const res = await request('/api/posts?_limit=0');
|
| 433 |
+
expect(res.status).toBe(400);
|
| 434 |
+
expect(res.body.error).toBe('Invalid _limit: must be a positive integer');
|
| 435 |
+
});
|
| 436 |
+
|
| 437 |
+
it('GET /api/posts?_page=&_limit=1 handles empty string by deleting param', async () => {
|
| 438 |
+
const res = await request('/api/posts?_page=&_limit=1');
|
| 439 |
+
expect(res.status).toBe(200);
|
| 440 |
+
expect(res.body.length).toBe(1);
|
| 441 |
+
});
|
| 442 |
+
});
|
| 443 |
+
|
| 444 |
+
describe('Search', () => {
|
| 445 |
+
it('GET /api/posts?q=first searches body content', async () => {
|
| 446 |
+
const res = await request('/api/posts?q=first');
|
| 447 |
+
expect(res.status).toBe(200);
|
| 448 |
+
expect(res.body.length).toBe(1);
|
| 449 |
+
expect(res.body[0].title).toBe('Patched Title');
|
| 450 |
+
});
|
| 451 |
+
|
| 452 |
+
it('GET /api/todos?q=groceries finds matching todos', async () => {
|
| 453 |
+
const res = await request('/api/todos?q=groceries');
|
| 454 |
+
expect(res.status).toBe(200);
|
| 455 |
+
expect(res.body.length).toBe(1);
|
| 456 |
+
expect(res.body[0].title).toBe('Buy groceries');
|
| 457 |
+
});
|
| 458 |
+
|
| 459 |
+
it('GET /api/posts?q=Post&userId=1 combines search and filter', async () => {
|
| 460 |
+
const res = await request('/api/posts?q=Post&userId=1');
|
| 461 |
+
expect(res.status).toBe(200);
|
| 462 |
+
expect(res.body.length).toBe(2);
|
| 463 |
+
res.body.forEach((p) => {
|
| 464 |
+
expect(p.userId).toBe(1);
|
| 465 |
+
});
|
| 466 |
+
});
|
| 467 |
+
|
| 468 |
+
it('GET /api/posts?q=nonexistent returns empty array', async () => {
|
| 469 |
+
const res = await request('/api/posts?q=nonexistent');
|
| 470 |
+
expect(res.status).toBe(200);
|
| 471 |
+
expect(res.body.length).toBe(0);
|
| 472 |
+
});
|
| 473 |
+
});
|
| 474 |
+
|
| 475 |
+
describe('Sorting', () => {
|
| 476 |
+
it('GET /api/posts?_sort=title&_order=asc sorts ascending', async () => {
|
| 477 |
+
const res = await request('/api/posts?_sort=title&_order=asc');
|
| 478 |
+
expect(res.status).toBe(200);
|
| 479 |
+
expect(res.body.length).toBe(4);
|
| 480 |
+
expect(res.body[0].title).toBe('Custom ID');
|
| 481 |
+
expect(res.body[1].title).toBe('New Post');
|
| 482 |
+
expect(res.body[2].title).toBe('Patched Title');
|
| 483 |
+
expect(res.body[3].title).toBe('Replaced');
|
| 484 |
+
});
|
| 485 |
+
|
| 486 |
+
it('GET /api/posts?_sort=title&_order=desc sorts descending', async () => {
|
| 487 |
+
const res = await request('/api/posts?_sort=title&_order=desc');
|
| 488 |
+
expect(res.status).toBe(200);
|
| 489 |
+
expect(res.body.length).toBe(4);
|
| 490 |
+
expect(res.body[0].title).toBe('Replaced');
|
| 491 |
+
expect(res.body[1].title).toBe('Patched Title');
|
| 492 |
+
expect(res.body[2].title).toBe('New Post');
|
| 493 |
+
expect(res.body[3].title).toBe('Custom ID');
|
| 494 |
+
});
|
| 495 |
+
|
| 496 |
+
it('GET /api/posts?_sort=title defaults to asc', async () => {
|
| 497 |
+
const res = await request('/api/posts?_sort=title');
|
| 498 |
+
expect(res.status).toBe(200);
|
| 499 |
+
expect(res.body[0].title).toBe('Custom ID');
|
| 500 |
+
expect(res.body[1].title).toBe('New Post');
|
| 501 |
+
});
|
| 502 |
+
|
| 503 |
+
it('GET /api/posts?_sort=id&_order=desc&_limit=2 combines sort with pagination', async () => {
|
| 504 |
+
const res = await request('/api/posts?_sort=id&_order=desc&_limit=2');
|
| 505 |
+
expect(res.status).toBe(200);
|
| 506 |
+
expect(res.body.length).toBe(2);
|
| 507 |
+
expect(res.body[0].id).toBe(100);
|
| 508 |
+
expect(res.body[1].id).toBe(4);
|
| 509 |
+
});
|
| 510 |
+
});
|