expediate 1.0.0 → 1.0.1

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/.npmignore CHANGED
@@ -7,7 +7,8 @@
7
7
  node_modules/
8
8
  src/
9
9
  tests/
10
- !*.js
10
+ !src/*.js
11
+ !src/*.json
11
12
  !*.map
12
13
  !*.ts
13
14
  !package.json
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "expediate",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Web framework to create complete HTTP server.",
5
5
  "main": "dist/index.js",
6
6
  "type": "commonjs",
@@ -24,13 +24,12 @@
24
24
  },
25
25
  "repository": {
26
26
  "type": "git",
27
- "url": "https://github.com/AxFab/expediate"
27
+ "url": "git+https://github.com/AxFab/expediate.git"
28
28
  },
29
29
  "author": "Fabien Bavent <fabien.bavent@gmail.com>",
30
30
  "contributors": [],
31
31
  "license": "MIT",
32
- "dependencies": {
33
- },
32
+ "dependencies": {},
34
33
  "devDependencies": {
35
34
  "@types/node": "^25.5.0",
36
35
  "typescript": "^5.9.3",
package/src/apis.ts ADDED
@@ -0,0 +1,428 @@
1
+ /* Copyright 2021 Fabien Bavent
2
+ *
3
+ * Permission is hereby granted, free of charge, to any person obtaining a
4
+ * copy of this software and associated documentation files (the "Software"),
5
+ * to deal in the Software without restriction, including without limitation
6
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
7
+ * and/or sell copies of the Software, and to permit persons to whom the
8
+ * Software is furnished to do so, subject to the following conditions:
9
+ *
10
+ * The above copyright notice and this permission notice shall be included
11
+ * in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19
+ * DEALINGS IN THE SOFTWARE.
20
+ */
21
+ 'use strict';
22
+
23
+ import createRouter from './router.js';
24
+ import type { RouterRequest, RouterResponse, Router } from './router.js';
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // Types
28
+ // ---------------------------------------------------------------------------
29
+
30
+ /**
31
+ * An API error thrown (or rejected) by a service method.
32
+ *
33
+ * When a service method throws or rejects with an object of this shape, the
34
+ * framework translates it into an HTTP error response automatically:
35
+ * - `httpStatus` → HTTP status code (defaults to `500`).
36
+ * - `data` → JSON-serialised response body (takes precedence over `message`).
37
+ * - `message` → Plain-text response body.
38
+ */
39
+ export interface ApiError {
40
+ /** HTTP status code to send (e.g. `404`, `503`). Defaults to `500`. */
41
+ httpStatus?: number;
42
+ /** Structured error payload; serialised to JSON when present. */
43
+ data?: unknown;
44
+ /** Human-readable error message used when `data` is absent. */
45
+ message?: string;
46
+ }
47
+
48
+ /**
49
+ * A service method handler.
50
+ *
51
+ * Called with `this` bound to the current service instance.
52
+ *
53
+ * @param params - Route parameters extracted from the URL (e.g. `{ uid: '42' }`),
54
+ * merged with URL query-string parameters.
55
+ * @param body - Parsed request body (populated by a body-parsing middleware
56
+ * such as `json()`).
57
+ * @returns The value to send as the JSON response body, a `Promise` of the
58
+ * same, or `undefined` / `null` / any falsy value to send **201 No
59
+ * Content** (useful for mutations that produce no response body).
60
+ */
61
+ export type ServiceMethod<TInstance = ServiceInstance> = (
62
+ this: TInstance,
63
+ params: Record<string, string>,
64
+ body?: unknown,
65
+ ) => unknown | Promise<unknown>;
66
+
67
+ /**
68
+ * The runtime state object that backs a service instance.
69
+ *
70
+ * Produced by `service.data()` and extended with the methods from
71
+ * `service.methods` before `service.setup()` is called. A hidden `$key`
72
+ * property carries the scope key when `data()` is not supplied.
73
+ */
74
+ export type ServiceInstance = Record<string, unknown> & {
75
+ /** The scope key used to identify this instance (set by the framework). */
76
+ $key?: string | null;
77
+ };
78
+
79
+ /**
80
+ * A named map of method functions to mix into every service instance.
81
+ *
82
+ * Methods declared here are copied onto the instance object, bound to `this`,
83
+ * so they can call each other and read/write instance state naturally.
84
+ */
85
+ export type ServiceMethods<TInstance extends ServiceInstance = ServiceInstance> = {
86
+ [name: string]: (this: TInstance, ...args: unknown[]) => unknown;
87
+ };
88
+
89
+ /**
90
+ * A route map: keys are Express-style path patterns, values are handler
91
+ * functions that are invoked with `this` bound to the service instance.
92
+ */
93
+ export type RouteMap<TInstance extends ServiceInstance = ServiceInstance> = {
94
+ [path: string]: ServiceMethod<TInstance>;
95
+ };
96
+
97
+ /**
98
+ * A service definition object — the single argument to {@link apiBuilder}.
99
+ *
100
+ * A service declares its state, helper methods, and HTTP route handlers in
101
+ * one cohesive object. The framework instantiates the service (once globally
102
+ * for a singleton, or per-scope key), mixes in the helper methods, runs
103
+ * `setup()`, then calls the appropriate route handler for each HTTP request.
104
+ *
105
+ * **Scoping:**
106
+ * - When `scope` is **absent** (or not a function), the service is a
107
+ * **singleton**: one shared instance handles all requests.
108
+ * - When `scope` returns a **truthy string**, the same instance is reused
109
+ * for all requests that share that key (e.g. one instance per session).
110
+ * - When `scope` returns **`null`**, a **fresh instance** is created for
111
+ * every request and discarded afterwards (recommended for stateless services).
112
+ *
113
+ * @template TInstance - The shape of the service's state object.
114
+ */
115
+ export interface ServiceDefinition<TInstance extends ServiceInstance = ServiceInstance> {
116
+ /**
117
+ * Determine the scope key for the current request.
118
+ *
119
+ * - Return a **string** → instances are cached by that key (e.g. session ID).
120
+ * - Return **`null`** → create a new, disposable instance per request.
121
+ * - Omit entirely → the service is a **singleton** (one global instance).
122
+ *
123
+ * @example
124
+ * ```ts
125
+ * scope: (req) => (req as any).session?.ssid ?? null,
126
+ * ```
127
+ */
128
+ scope?: (req: RouterRequest) => string | null;
129
+
130
+ /**
131
+ * Factory that returns the initial state object for a new instance.
132
+ *
133
+ * When omitted, the instance is initialised as `{ $key: key }`.
134
+ *
135
+ * @param key - The scope key passed by the framework (`'singleton'` for
136
+ * global instances, `null` for ephemeral ones, or the string
137
+ * returned by `scope()`).
138
+ */
139
+ data?: (key: string | null) => TInstance;
140
+
141
+ /**
142
+ * Lifecycle hook called once after an instance is created and its methods
143
+ * are mixed in.
144
+ *
145
+ * May be synchronous or asynchronous. When asynchronous, the returned
146
+ * `Promise` is not awaited by the framework — use a `throwIfNotReady()`
147
+ * pattern in your methods to guard against premature access.
148
+ */
149
+ setup?: (this: TInstance) => void | Promise<void>;
150
+
151
+ /**
152
+ * Helper methods mixed into every service instance.
153
+ *
154
+ * All methods are bound to the instance (`this` = instance), so they can
155
+ * read and write state, call other methods, and throw {@link ApiError}
156
+ * objects to trigger HTTP error responses.
157
+ */
158
+ methods?: ServiceMethods<TInstance>;
159
+
160
+ /** Route handlers for `GET` requests. */
161
+ GET?: RouteMap<TInstance>;
162
+ /** Route handlers for `POST` requests. */
163
+ POST?: RouteMap<TInstance>;
164
+ /** Route handlers for `PUT` requests. */
165
+ PUT?: RouteMap<TInstance>;
166
+ /** Route handlers for `DELETE` requests. */
167
+ DELETE?: RouteMap<TInstance>;
168
+ /** Route handlers for `PATCH` requests. */
169
+ PATCH?: RouteMap<TInstance>;
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // Internal helpers
174
+ // ---------------------------------------------------------------------------
175
+
176
+ /**
177
+ * Instantiate a new service module for the given scope `key`.
178
+ *
179
+ * The lifecycle is:
180
+ * 1. **`data(key)`** — create the initial state object (or use `{ $key: key }`
181
+ * when `data` is not defined).
182
+ * 2. **Mix in methods** — each entry in `service.methods` is copied onto the
183
+ * instance as a regular function bound to `this`.
184
+ * 3. **`setup()`** — called once on the new instance; may be async.
185
+ *
186
+ * @param service - The service definition.
187
+ * @param key - The scope key (`'singleton'`, `null`, or a session ID).
188
+ * @returns A fully initialised service instance.
189
+ */
190
+ function buildModule<TInstance extends ServiceInstance>(
191
+ service: ServiceDefinition<TInstance>,
192
+ key: string | null,
193
+ ): TInstance {
194
+ const instance: TInstance = service.data
195
+ ? service.data(key)
196
+ : ({ $key: key } as unknown as TInstance);
197
+
198
+ // Mix service methods into the instance, bound to `this = instance`.
199
+ // BUG FIX: the original used arrow functions `() => method.apply(module, arguments)`.
200
+ // Arrow functions do NOT have their own `arguments` object — they inherit it
201
+ // from the enclosing `buildModule` scope (which holds `(service, key)`).
202
+ // Any arguments forwarded to the method were therefore silently dropped.
203
+ // Corrected to a regular function expression that captures its own `arguments`
204
+ // via a rest parameter spread.
205
+ if (service.methods) {
206
+ for (const methodName of Object.keys(service.methods)) {
207
+ const method = service.methods[methodName];
208
+ (instance as Record<string, unknown>)[methodName] = function (
209
+ this: TInstance,
210
+ ...args: unknown[]
211
+ ): unknown {
212
+ return method.apply(instance, args);
213
+ };
214
+ }
215
+ }
216
+
217
+ if (service.setup)
218
+ service.setup.apply(instance, [] as []);
219
+
220
+ return instance;
221
+ }
222
+
223
+ /**
224
+ * Resolve the correct service instance for an incoming request.
225
+ *
226
+ * Instance lifecycle by scope:
227
+ * - **Singleton** (`scope` absent): always returns `modules['singleton']`.
228
+ * - **Keyed** (`scope` returns a string): look up `modules[key]`; create and
229
+ * cache a new instance on first access.
230
+ * - **Ephemeral** (`scope` returns `null`): create a fresh instance every time;
231
+ * never cached.
232
+ *
233
+ * @param service - The service definition.
234
+ * @param modules - The instance cache (mutated when a new keyed instance is created).
235
+ * @param req - The incoming request.
236
+ * @returns The service instance to use for this request.
237
+ */
238
+ function resolveInstance<TInstance extends ServiceInstance>(
239
+ service: ServiceDefinition<TInstance>,
240
+ modules: Record<string, TInstance>,
241
+ req: RouterRequest,
242
+ ): TInstance {
243
+ if (typeof service.scope !== 'function') {
244
+ // Singleton — always the same global instance.
245
+ return modules['singleton'];
246
+ }
247
+
248
+ // BUG FIX: the original called `service.key(req)` which does not exist on
249
+ // the service definition. The correct method is `service.scope(req)`.
250
+ const key = service.scope(req);
251
+
252
+ if (key === null) {
253
+ // Ephemeral — create a fresh, uncached instance for every request.
254
+ return buildModule(service, null);
255
+ }
256
+
257
+ // Keyed — retrieve from cache or create and store.
258
+ if (!modules[key])
259
+ modules[key] = buildModule(service, key);
260
+
261
+ return modules[key];
262
+ }
263
+
264
+ // ---------------------------------------------------------------------------
265
+ // Response helpers
266
+ // ---------------------------------------------------------------------------
267
+
268
+ /**
269
+ * Send a JSON response with the appropriate `Content-Type` header.
270
+ *
271
+ * @param res - The outgoing response.
272
+ * @param data - Any JSON-serialisable value.
273
+ */
274
+ function sendJson(res: RouterResponse, data: unknown): void {
275
+ // BUG FIX: the original called `res.send(JSON.stringify(val))` without
276
+ // setting a `Content-Type` header. Clients had no way to detect that the
277
+ // response body was JSON. Corrected by setting the header explicitly.
278
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
279
+ res.send(JSON.stringify(data));
280
+ }
281
+
282
+ /**
283
+ * Translate a caught error (thrown or rejected by a service method) into an
284
+ * HTTP error response.
285
+ *
286
+ * Expected shape: `{ httpStatus?, data?, message? }` (see {@link ApiError}).
287
+ * Any other thrown value is treated as an opaque 500 Internal Server Error.
288
+ *
289
+ * @param res - The outgoing response.
290
+ * @param err - The caught value.
291
+ */
292
+ function sendError(res: RouterResponse, err: unknown): void {
293
+ const e = err as ApiError | undefined;
294
+ const status = e?.httpStatus ?? 500;
295
+ if (e?.data !== undefined) {
296
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
297
+ res.status(status).send(JSON.stringify(e.data));
298
+ } else {
299
+ res.status(status).send(e?.message ?? 'Internal error');
300
+ }
301
+ }
302
+
303
+ // ---------------------------------------------------------------------------
304
+ // Public API
305
+ // ---------------------------------------------------------------------------
306
+
307
+ /**
308
+ * Build an Express-compatible router from a service definition object.
309
+ *
310
+ * The returned router is suitable for mounting via `app.use()`:
311
+ *
312
+ * ```ts
313
+ * import myService from './my-service.js';
314
+ *
315
+ * app.use('/api', apiBuilder(myService));
316
+ * ```
317
+ *
318
+ * **Route handlers** declared in `service.GET`, `service.POST`, etc. are
319
+ * called with `this` bound to the service instance. They receive two
320
+ * arguments:
321
+ * 1. `params` — merged route + query-string parameters from `req.params`.
322
+ * 2. `body` — the parsed request body from `req.body` (requires a
323
+ * body-parsing middleware such as `json()` to run first).
324
+ *
325
+ * **Return values:**
326
+ * - A **truthy value** (or a `Promise` resolving to one) → serialised as JSON
327
+ * with status `200 OK`.
328
+ * - A **falsy value** (`undefined`, `null`, `false`, `0`, `''`) or a
329
+ * `Promise` resolving to one → `201 No Content` (useful for mutations).
330
+ *
331
+ * **Error handling:**
332
+ * - Throwing or rejecting with `{ httpStatus, message }` sends the
333
+ * corresponding HTTP error.
334
+ * - Throwing or rejecting with `{ httpStatus, data }` sends the `data` object
335
+ * as a JSON body.
336
+ * - Any other thrown value produces `500 Internal Server Error`.
337
+ *
338
+ * @param service - The service definition (see {@link ServiceDefinition}).
339
+ * @returns A router instance pre-configured with all declared routes.
340
+ */
341
+ export function apiBuilder<TInstance extends ServiceInstance = ServiceInstance>(
342
+ service: ServiceDefinition<TInstance>,
343
+ ): Router {
344
+ const api = createRouter();
345
+ const modules: Record<string, TInstance> = {};
346
+
347
+ // Pre-build the singleton instance eagerly so `setup()` runs at startup.
348
+ if (typeof service.scope !== 'function')
349
+ // BUG FIX: the original called `buildModule(service)` without a key,
350
+ // passing `undefined` to `data()` and leaving `$key` as `undefined`.
351
+ // Corrected to pass `'singleton'` as the canonical key.
352
+ modules['singleton'] = buildModule(service, 'singleton');
353
+
354
+ /**
355
+ * Register all route handlers from a route map for a given HTTP method.
356
+ *
357
+ * Each handler:
358
+ * 1. Resolves the correct service instance (singleton / keyed / ephemeral).
359
+ * 2. Invokes the service method with `(params, body)`.
360
+ * 3. Sends the return value as JSON (or 201 if falsy).
361
+ * 4. Catches thrown / rejected {@link ApiError} objects and translates them
362
+ * into the appropriate HTTP error response.
363
+ *
364
+ * @param routeMap - Map of path patterns to service methods (`undefined` = skip).
365
+ * @param register - Registers a handler on the router for the current HTTP method.
366
+ */
367
+ function buildRoutes(
368
+ routeMap: RouteMap<TInstance> | undefined,
369
+ register: (path: string, handler: (req: RouterRequest, res: RouterResponse) => void) => void,
370
+ ): void {
371
+ if (!routeMap) return;
372
+
373
+ // Sort routes by decreasing specificity so that more precise patterns
374
+ // (more segments, fewer parameters) are registered first in the router.
375
+ // Without this, a plain path like '/items' would match '/items/1' as a
376
+ // prefix and steal requests intended for '/items/:id'.
377
+ // Specificity = (segment count * 100) - (parameter count * 10).
378
+ const sortedPaths = Object.keys(routeMap).sort((a, b) => {
379
+ const score = (p: string) => {
380
+ const segs = p.split('/').filter(s => s.length > 0);
381
+ return segs.length * 100 - segs.filter(s => s.startsWith(':')).length * 10;
382
+ };
383
+ return score(b) - score(a) || b.localeCompare(a);
384
+ });
385
+
386
+ for (const path of sortedPaths) {
387
+ const method = routeMap[path];
388
+
389
+ register(path, (req: RouterRequest, res: RouterResponse): void => {
390
+ const params = req.params as Record<string, string>;
391
+ const body = (req as any).body;
392
+
393
+ try {
394
+ const instance = resolveInstance(service, modules, req);
395
+ const ret = method.apply(instance, [params, body]);
396
+
397
+ if (ret instanceof Promise) {
398
+ ret
399
+ .then((val) => {
400
+ if (val !== undefined && val !== null && val !== false && val !== 0 && val !== '')
401
+ sendJson(res, val);
402
+ else
403
+ res.status(201).end();
404
+ })
405
+ .catch((err) => sendError(res, err));
406
+ } else {
407
+ if (ret !== undefined && ret !== null && ret !== false && ret !== 0 && ret !== '')
408
+ sendJson(res, ret);
409
+ else
410
+ res.status(201).end();
411
+ }
412
+ } catch (err) {
413
+ sendError(res, err);
414
+ }
415
+ });
416
+ }
417
+ }
418
+
419
+ buildRoutes(service.GET, (path, h) => api.get(path, h as any));
420
+ buildRoutes(service.POST, (path, h) => api.post(path, h as any));
421
+ buildRoutes(service.PUT, (path, h) => api.put(path, h as any));
422
+ buildRoutes(service.DELETE, (path, h) => api.delete(path, h as any));
423
+ buildRoutes(service.PATCH, (path, h) => api.patch(path, h as any));
424
+
425
+ return api;
426
+ }
427
+
428
+ export default apiBuilder;