tr-apisrv 1.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +254 -68
- package/index.js +700 -70
- package/package.json +1 -1
- package/test/test.js +952 -10
package/README.md
CHANGED
|
@@ -1,98 +1,284 @@
|
|
|
1
|
-
API Server
|
|
2
|
-
==========
|
|
1
|
+
# API Server
|
|
3
2
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
`tr-apisrv` is a lightweight JSON-oriented HTTP(S) server that focuses on fast
|
|
4
|
+
configuration and predictable request handling rules. It supports declarative
|
|
5
|
+
handler registration, request parameter validation, and pluggable
|
|
6
|
+
authentication, making it easy to bootstrap small services or mock APIs.
|
|
7
7
|
|
|
8
|
-
Requires Node.js 18 or newer
|
|
8
|
+
Requires **Node.js 18 or newer**.
|
|
9
9
|
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install tr-apisrv
|
|
10
14
|
```
|
|
15
|
+
|
|
16
|
+
## Quick start
|
|
17
|
+
|
|
18
|
+
```javascript
|
|
11
19
|
const ApiSrv = require('tr-apisrv');
|
|
12
20
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
authCallback: authCb,
|
|
17
|
-
prettyPrintJsonResponses: true,
|
|
18
|
-
bodyReadTimeoutMs: 5000,
|
|
19
|
-
maxBodySize: 1024 * 1024,
|
|
20
|
-
debug: true });
|
|
21
|
-
|
|
22
|
-
async function authCb(r) {
|
|
23
|
-
return true;
|
|
21
|
+
async function authenticate(request) {
|
|
22
|
+
// return false to reject the request
|
|
23
|
+
return request.headers.authorization === 'Bearer secret-token';
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
async function
|
|
27
|
-
|
|
26
|
+
async function listUsers(request) {
|
|
27
|
+
// Access individual parameter sources or the merged view
|
|
28
|
+
return request.jsonResponse({
|
|
29
|
+
params: request.params,
|
|
30
|
+
path: request.pathParams,
|
|
31
|
+
query: request.urlParams,
|
|
32
|
+
body: request.bodyParams
|
|
33
|
+
});
|
|
28
34
|
}
|
|
35
|
+
|
|
36
|
+
async function fallback(request) {
|
|
37
|
+
return request.jsonResponse({ message: 'Fallback handler invoked' });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const server = new ApiSrv({
|
|
41
|
+
port: 8808,
|
|
42
|
+
address: '127.0.0.1',
|
|
43
|
+
authCallback: authenticate,
|
|
44
|
+
callback: fallback,
|
|
45
|
+
requestHandlers: {
|
|
46
|
+
GET: {
|
|
47
|
+
'/users': listUsers,
|
|
48
|
+
'/users/{userId}': listUsers,
|
|
49
|
+
'/files/[path]': {
|
|
50
|
+
callback: listUsers,
|
|
51
|
+
options: {
|
|
52
|
+
paramsValidator: (params) => ({ ...params, validated: true })
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
});
|
|
29
58
|
```
|
|
30
59
|
|
|
31
|
-
|
|
32
|
-
|
|
60
|
+
Requests are matched against `requestHandlers` first. When no handler matches,
|
|
61
|
+
the optional top-level `callback` is used as a fallback. If neither resolves the
|
|
62
|
+
request, `tr-apisrv` returns a canonical JSON error such as
|
|
63
|
+
`{"code":404,"message":"Not Found"}`.
|
|
64
|
+
|
|
65
|
+
## Configuration reference
|
|
66
|
+
|
|
67
|
+
| Option | Type | Default | Description |
|
|
68
|
+
| --- | --- | --- | --- |
|
|
69
|
+
| `port` | number | **required** | TCP port to listen on (1–65535). |
|
|
70
|
+
| `address` | string | `undefined` | Local address to bind. Leave undefined to listen on all interfaces. |
|
|
71
|
+
| `key` / `cert` | string | Buffer | `undefined` | Provide both to enable HTTPS. Supplying only one throws an error. |
|
|
72
|
+
| `callback` | function | `undefined` | Fallback handler when no `requestHandlers` entry matches. |
|
|
73
|
+
| `requestHandlers` | object | `undefined` | Declarative handler map, keyed by HTTP method. Details below. |
|
|
74
|
+
| `authCallback` | function | `() => true` | Runs before any parameters are parsed. Return truthy to continue; falsy lets you reject (e.g. send 401). Parameter fields are `undefined` during this callback. |
|
|
75
|
+
| `upgradeCallback` | function | `undefined` | Optional `upgrade` (e.g. WebSocket) handler invoked after authentication. |
|
|
76
|
+
| `prettyPrintJsonResponses` | boolean | `false` | When true, `jsonResponse` pretty-prints JSON with trailing newline. |
|
|
77
|
+
| `rejectDangerousPaths` | boolean | `true` | Reject paths containing empty, `.` or `..` segments with HTTP 400. |
|
|
78
|
+
| `bodyReadTimeoutMs` | number | `2000` | Milliseconds allowed to fully read the request body. Applies to upgrade as well. |
|
|
79
|
+
| `maxBodySize` | number | `1048576` | Maximum allowed request body size in bytes. `0` allows only empty bodies. |
|
|
80
|
+
| `debug` | boolean | `false` | Enables verbose logging for authentication failures and handler completion. |
|
|
81
|
+
|
|
82
|
+
The server accepts only `GET`, `POST`, `PUT`, and `DELETE` requests. Other
|
|
83
|
+
methods receive `405 Method Not Allowed`.
|
|
84
|
+
|
|
85
|
+
## Request handler definitions
|
|
86
|
+
|
|
87
|
+
Each HTTP method in `requestHandlers` maps path templates to either a callback
|
|
88
|
+
function or an object of the shape `{ callback, options }`. Callbacks receive the
|
|
89
|
+
request wrapper described in [Request object](#request-object).
|
|
90
|
+
|
|
91
|
+
### Resolution order
|
|
33
92
|
|
|
34
|
-
|
|
35
|
-
|
|
93
|
+
1. Match the request method and path against `requestHandlers`.
|
|
94
|
+
2. If no handler matches and a top-level `callback` exists, it handles the request.
|
|
95
|
+
3. When neither resolves the request, `tr-apisrv` returns a JSON error. A `405 Method Not Allowed`
|
|
96
|
+
response is used when another method is registered for the same path; otherwise
|
|
97
|
+
the response is `404 Not Found`.
|
|
98
|
+
|
|
99
|
+
### Path templates
|
|
100
|
+
|
|
101
|
+
Path templates determine which requests reach a handler and how parameters are
|
|
102
|
+
extracted. All templates must start with `/`.
|
|
103
|
+
Method keys in `requestHandlers` should be uppercase (`GET`, `POST`, `PUT`, `DELETE`).
|
|
104
|
+
|
|
105
|
+
* **Literal segments** – `/users/list` matches exactly that path.
|
|
106
|
+
* **Single-segment captures** – `{name}` captures one path component and makes it
|
|
107
|
+
available as a string. Capture names must match the regular expression
|
|
108
|
+
`/^[A-Za-z_][A-Za-z0-9_]*$/`. Example: `/users/{userId}` matches `/users/123`
|
|
109
|
+
and sets `request.pathParams.userId === '123'`.
|
|
110
|
+
* **Multi-segment captures** – `[name]` captures one or more consecutive
|
|
111
|
+
segments and exposes them as an array of strings. Names follow the same
|
|
112
|
+
pattern restriction as `{name}`. Arrays match 1–32 segments by default, and
|
|
113
|
+
you can provide explicit bounds with `[name:min]` (exact length) or
|
|
114
|
+
`[name:min:max]` (inclusive range). Examples:
|
|
115
|
+
* `/example/path/[MyArray]` matches 1 to 32 segments.
|
|
116
|
+
* `/example/path/[MyArray:4]` matches exactly four segments.
|
|
117
|
+
* `/example/path/[MyArray:2:12]` matches two to twelve segments.
|
|
118
|
+
* `/example/path/[MyArray:10:50]` matches ten to fifty segments, allowing
|
|
119
|
+
larger maxima than the default. The upper bound is always finite—either the
|
|
120
|
+
default 32 or the explicit maximum you declare.
|
|
121
|
+
* Captures can be combined with literals, e.g. `/{cmd}/[args]/{tail}`. When
|
|
122
|
+
combined, `[args]` consumes all necessary segments so the remaining template
|
|
123
|
+
still matches.
|
|
124
|
+
|
|
125
|
+
Trailing slashes are significant only when they appear in the template:
|
|
126
|
+
|
|
127
|
+
* `/users/` matches `/users/` but not `/users`.
|
|
128
|
+
* `/users` matches both `/users` and `/users/`.
|
|
129
|
+
|
|
130
|
+
All captured values are URL-decoded. If decoding fails, the request is rejected
|
|
131
|
+
with HTTP 400.
|
|
132
|
+
|
|
133
|
+
### Handler options
|
|
134
|
+
|
|
135
|
+
`options` fine-tune validation and query-string handling. Every option is
|
|
136
|
+
optional; validators may be synchronous or asynchronous and must return the
|
|
137
|
+
processed object. Throwing from a validator results in `400 Bad Request`. Returning
|
|
138
|
+
anything other than an object causes a `500` response noting the validator must
|
|
139
|
+
return an object.
|
|
140
|
+
|
|
141
|
+
| Option | Description |
|
|
142
|
+
| --- | --- |
|
|
143
|
+
| `pathParamsValidator` | Validates and can transform `request.pathParams`. |
|
|
144
|
+
| `urlParamsValidator` | Validates and can transform `request.urlParams`. Not called when `ignoreUrlParams` is `true`. |
|
|
145
|
+
| `bodyParamsValidator` | Validates and can transform `request.bodyParams`. |
|
|
146
|
+
| `paramsValidator` | Validates the merged `request.params` object. |
|
|
147
|
+
| `ignoreUrlParams` | When `true`, the query string is ignored and `request.urlParams` is left `undefined`. |
|
|
148
|
+
|
|
149
|
+
#### Validator example
|
|
36
150
|
|
|
37
151
|
```javascript
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
152
|
+
server.requestHandleAdd('GET', '/reports/{id}', fetchReport, {
|
|
153
|
+
pathParamsValidator: (params) => ({ id: Number(params.id) }),
|
|
154
|
+
urlParamsValidator: async (query) => ({ ...query, limit: Number(query.limit ?? 10) }),
|
|
155
|
+
paramsValidator: (params) => ({ ...params, filtered: true })
|
|
156
|
+
});
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Validators can perform type coercion or enforce business rules before the
|
|
160
|
+
handler runs. Throwing inside any validator (including asynchronous ones)
|
|
161
|
+
returns `400 Bad Request` with the error message appended in parentheses.
|
|
162
|
+
|
|
163
|
+
Use `ignoreUrlParams` to opt out of query-string parsing entirely:
|
|
164
|
+
|
|
165
|
+
```javascript
|
|
166
|
+
server.requestHandleAdd('POST', '/import', importHandler, {
|
|
167
|
+
ignoreUrlParams: true,
|
|
168
|
+
bodyParamsValidator: validateImportPayload
|
|
169
|
+
});
|
|
49
170
|
```
|
|
50
171
|
|
|
51
|
-
|
|
52
|
-
|
|
172
|
+
You can supply the same `options` when adding handlers at runtime with
|
|
173
|
+
`requestHandleAdd(method, path, callback, options)`.
|
|
174
|
+
|
|
175
|
+
### Runtime updates
|
|
176
|
+
|
|
177
|
+
Handlers may be added, replaced, or removed without restarting the process:
|
|
53
178
|
|
|
54
179
|
```javascript
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
}
|
|
180
|
+
server.requestHandleAdd('GET', '/status', statusHandler);
|
|
181
|
+
server.requestHandleAdd('POST', '/status', statusHandler, {
|
|
182
|
+
bodyParamsValidator: (body) => ({ ...body, updatedAt: Date.now() })
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
// Remove a single method
|
|
186
|
+
server.requestHandleDelete('POST', '/status');
|
|
187
|
+
|
|
188
|
+
// Remove all methods for a path
|
|
189
|
+
server.requestHandleDelete('*', '/status');
|
|
66
190
|
```
|
|
67
191
|
|
|
68
|
-
|
|
69
|
-
|
|
192
|
+
## Request object
|
|
193
|
+
|
|
194
|
+
Handlers receive an object that wraps the underlying `http.IncomingMessage` and
|
|
195
|
+
`http.ServerResponse`.
|
|
196
|
+
|
|
197
|
+
| Property | Description |
|
|
198
|
+
| --- | --- |
|
|
199
|
+
| `method` | Uppercase HTTP method. |
|
|
200
|
+
| `url` | Request path without the query string. |
|
|
201
|
+
| `req` | The raw `http.IncomingMessage`. |
|
|
202
|
+
| `res` | The raw `http.ServerResponse`. |
|
|
203
|
+
| `headers` | Request headers as received. |
|
|
204
|
+
| `jsonResponse(data, statusCode?, excludeNoCacheHeaders?)` | Serializes JSON responses and sets default no-cache headers unless `excludeNoCacheHeaders` is `true`. |
|
|
205
|
+
| `errorResponse(statusCode, detail?)` | Sends a JSON error using canonical HTTP status text. For `400 Bad Request`, the optional detail is appended in parentheses. |
|
|
206
|
+
| `params` | Merged view of all parameters (body < query < path precedence). |
|
|
207
|
+
| `pathParams` | Parameters parsed from the matched path template. |
|
|
208
|
+
| `urlParams` | Parsed query parameters (unless suppressed). Arrays are preserved when the query repeats a key. |
|
|
209
|
+
| `bodyParams` | Parsed request body, when provided. |
|
|
210
|
+
|
|
211
|
+
During `authCallback`, the server has not parsed any parameters. At that point
|
|
212
|
+
`request.params`, `request.pathParams`, `request.urlParams`, and
|
|
213
|
+
`request.bodyParams` are all `undefined`. They are populated only after
|
|
214
|
+
authentication succeeds and before the handler runs.
|
|
215
|
+
|
|
216
|
+
All parameter collections are plain objects (or arrays for multi-segment
|
|
217
|
+
captures). Parameters are merged in the following order: body → query string →
|
|
218
|
+
path. Later sources override earlier ones in `request.params`. When this occurs,
|
|
219
|
+
`tr-apisrv` logs a warning naming both sources.
|
|
70
220
|
|
|
71
|
-
|
|
72
|
-
|
|
221
|
+
## Body parsing and limits
|
|
222
|
+
|
|
223
|
+
* `POST` and `PUT` bodies must use `application/json` or
|
|
224
|
+
`application/x-www-form-urlencoded`. Other types result in
|
|
225
|
+
`400 Bad Request (POST or PUT body must be in JSON or www-form-urlencoded format.)`.
|
|
226
|
+
* `GET` and `DELETE` requests must not include a body.
|
|
227
|
+
* Bodies larger than `maxBodySize` yield `413 Payload Too Large`.
|
|
228
|
+
* Slow clients that exceed `bodyReadTimeoutMs` cause `408 Request Timeout`.
|
|
229
|
+
|
|
230
|
+
## Authentication and upgrades
|
|
231
|
+
|
|
232
|
+
Before a handler runs, `authCallback` is awaited with the request object. During
|
|
233
|
+
this phase the parameter properties remain `undefined`; they are parsed only
|
|
234
|
+
after authentication succeeds. Returning a falsy value lets you send your own
|
|
235
|
+
response (for example, `401 Unauthorized`) and skips the handler. The callback
|
|
236
|
+
can still mutate the request object, such as attaching user information for the
|
|
237
|
+
handler to consume.
|
|
238
|
+
|
|
239
|
+
When `upgradeCallback` is provided, upgrade requests (e.g. WebSocket handshakes)
|
|
240
|
+
follow the same sequence: authentication runs first with the parameter
|
|
241
|
+
properties unset. Once the callback allows the upgrade, query parameters are
|
|
242
|
+
parsed and provided alongside `req`, `s`, and `head` before invoking the upgrade
|
|
243
|
+
handler.
|
|
244
|
+
|
|
245
|
+
## Error handling
|
|
246
|
+
|
|
247
|
+
Errors generated by `tr-apisrv` itself always use JSON with canonical HTTP
|
|
248
|
+
status text in the `message` property, for example:
|
|
249
|
+
|
|
250
|
+
```json
|
|
251
|
+
{ "code": 404, "message": "Not Found" }
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
Additional context is appended in parentheses for 400-series validation errors,
|
|
255
|
+
matching the format `"Bad Request (detailed reason)"`.
|
|
256
|
+
|
|
257
|
+
Handlers remain free to craft any response, including non-JSON payloads, by using
|
|
258
|
+
`request.res` directly. The convenience method `jsonResponse` is suitable for
|
|
259
|
+
most use cases:
|
|
73
260
|
|
|
74
261
|
```javascript
|
|
75
|
-
async function
|
|
76
|
-
|
|
77
|
-
r.res.writeHead(200, { 'Content-Type': 'text/plain' });
|
|
78
|
-
r.res.end('ok');
|
|
79
|
-
return;
|
|
80
|
-
}
|
|
81
|
-
// default JSON response
|
|
82
|
-
return r.jsonResponse({ ok: true });
|
|
262
|
+
async function ping(request) {
|
|
263
|
+
return request.jsonResponse({ ok: true });
|
|
83
264
|
}
|
|
84
265
|
```
|
|
85
266
|
|
|
86
|
-
|
|
87
|
-
the limit are terminated with HTTP status 413. The default limit is 1 MiB.
|
|
267
|
+
## Safety features
|
|
88
268
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
269
|
+
When `rejectDangerousPaths` is `true` (the default), the server rejects paths
|
|
270
|
+
containing empty segments (`//`) or dot segments (`/.`, `/..`) before running
|
|
271
|
+
authentication or handlers. Disable the check only when you know that upstream
|
|
272
|
+
routing has already sanitized paths:
|
|
93
273
|
|
|
274
|
+
```javascript
|
|
275
|
+
const srv = new ApiSrv({
|
|
276
|
+
port: 8808,
|
|
277
|
+
rejectDangerousPaths: false,
|
|
278
|
+
callback: handler
|
|
279
|
+
});
|
|
280
|
+
```
|
|
94
281
|
|
|
95
|
-
License
|
|
96
|
-
=======
|
|
282
|
+
## License
|
|
97
283
|
|
|
98
|
-
MIT
|
|
284
|
+
MIT
|