@molecule/api-resource-article 1.1.6 → 1.2.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 CHANGED
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
3
  Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
4
  Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
5
  To change this document, edit the module-level JSDoc in src/index.ts.
6
- Generated: 2026-10-25T00:22:04.478Z
6
+ Generated: 2026-11-06T22:46:11.711Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-resource-article
@@ -44,17 +44,27 @@ import { routes, requestHandlerMap } from '@molecule/api-resource-article'
44
44
  ```
45
45
 
46
46
  ```typescript
47
- // An API with its own response shape (a spec you must match) uses the
48
- // service and writes its own envelope:
49
- import { createArticle, listArticles } from '@molecule/api-resource-article'
47
+ // Configure a publishing API's envelopes without rewriting its operations:
48
+ import { createArticleHandlers } from '@molecule/api-resource-article'
50
49
 
51
- router.post('/api/articles', authenticate, async (req, res) => {
52
- const article = await createArticle(userId, req.body.article)
53
- res.status(201).json({ article: { ...article, author: await profileOf(article.authorId) } })
50
+ const publishing = createArticleHandlers({
51
+ mapRequest: (req) => ({ body: req.body?.entry }),
52
+ mapResponse: async (result) => {
53
+ // Preserve validation, authorization, missing rows and empty deletes.
54
+ if (result.statusCode >= 400 || result.statusCode === 204) return result
55
+ // The app owns its projection. A list can batch-load author profiles here.
56
+ return { ...result, body: { entry: result.body } }
57
+ },
54
58
  })
59
+ router.post('/entries', publishing.create) // authenticated session remains required
60
+ router.get('/entries/:slug', publishing.read)
55
61
 
56
- const page = await listArticles({ tag: 'dragons', limit: 20, offset: 0, viewerId })
57
- // page.data[0].favorited, page.data[0].favoritesCount, page.total
62
+ // mapRequest can also resolve an external filter name to a user id in req.query.
63
+ // If a lookup finds nothing, return { response: { statusCode, body } } with
64
+ // this API's empty-page response before querying. Never drop the filter.
65
+ // Keep extra domain validation in route middleware before these handlers.
66
+ // For a different domain model or custom workflow, call createArticle/listArticles
67
+ // from a local route instead. The default requestHandlerMap never adopts these mappings.
58
68
  ```
59
69
 
60
70
  ```typescript
@@ -227,97 +237,42 @@ interface TagCount {
227
237
 
228
238
  ### Types
229
239
 
230
- #### `AuthorChange`
231
-
232
- The outcome of a change that only the author may make.
233
-
234
- ```typescript
235
- type AuthorChange<T> =
236
- { status: 'ok'; article: T } | { status: 'not_found' } | { status: 'forbidden' }
237
- ```
238
-
239
- ### Functions
240
-
241
- #### `create(req, res)`
242
-
243
- `POST /articles` — create an article as the signed-in user.
244
-
245
- ```typescript
246
- function create(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
247
- ```
248
-
249
- - `req` — Body: `{ title, body, description?, tagList? }`.
250
- - `res` — 201 with the article.
251
-
252
- #### `list(req, res)`
240
+ #### `ArticleRequestHandlerMap`
253
241
 
254
- `GET /articles` — newest first; `?tag=`, `?author=` (user id),
255
- `?favoritedBy=` (user id), `?limit=`, `?offset=`.
242
+ HTTP handlers for all article routes. Authorization stays in each operation.
256
243
 
257
244
  ```typescript
258
- function list(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
259
- ```
260
-
261
- - `req` — The request.
262
- - `res` — `{ data, total, limit, offset }`.
263
-
264
- #### `feed(req, res)`
265
-
266
- `GET /articles/feed` — articles by the authors the signed-in user follows.
267
-
268
- ```typescript
269
- function feed(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
270
- ```
271
-
272
- - `req` — `?limit=`, `?offset=`.
273
- - `res` — `{ data, total, limit, offset }`.
274
-
275
- #### `tags(req, res)`
276
-
277
- `GET /articles/tags` — every tag in use, most-used first.
278
-
279
- With no `?limit=` this is the whole list, the shape RealWorld's `GET /tags`
280
- asks for; `?limit=` narrows it to that many most-used tags.
281
-
282
- ```typescript
283
- function tags(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
245
+ type ArticleRequestHandlerMap = {
246
+ [Name in keyof typeof operations]: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
247
+ }
284
248
  ```
285
249
 
286
- - `req` — The request; `?limit=` caps the list.
287
- - `res` — `[{ tag, count }]`.
288
-
289
- #### `read(req, res)`
250
+ #### `AuthorChange`
290
251
 
291
- `GET /articles/:slug`.
252
+ The outcome of a change that only the author may make.
292
253
 
293
254
  ```typescript
294
- function read(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
255
+ type AuthorChange<T> =
256
+ { status: 'ok'; article: T } | { status: 'not_found' } | { status: 'forbidden' }
295
257
  ```
296
258
 
297
- - `req` — The request.
298
- - `res` — The article, or 404.
259
+ ### Functions
299
260
 
300
- #### `update(req, res)`
261
+ #### `createArticleHandlers(options)`
301
262
 
302
- `PUT /articles/:slug` — author only; a new title gives a new slug.
263
+ Create article handlers for this project's wire format. Adapt an envelope,
264
+ filter names or response projection without rewriting the article operations.
265
+ Each mapping receives the adapted request and its original response context.
266
+ Omit the options for the standard flat-body, raw-article and paginated-list API.
267
+ Error and partial responses reach mapResponse too, so preserve them explicitly.
303
268
 
304
269
  ```typescript
305
- function update(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
270
+ function createArticleHandlers(options?: RequestHandlerOptions): ArticleRequestHandlerMap
306
271
  ```
307
272
 
308
- - `req` — Body: any of `{ title, description, body, tagList }`.
309
- - `res` — The updated article, 403 or 404.
310
-
311
- #### `del(req, res)`
273
+ - `options` — Shared resource request/response mappings, scoped to this map.
312
274
 
313
- `DELETE /articles/:slug` — author only.
314
-
315
- ```typescript
316
- function del(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
317
- ```
318
-
319
- - `req` — The request.
320
- - `res` — 204, 403 or 404.
275
+ **Returns:** A route-compatible map with the same names as requestHandlerMap.
321
276
 
322
277
  #### `hydrateArticles(rows, viewerId)`
323
278
 
@@ -497,9 +452,65 @@ function popularTags(limit?: number): Promise<TagCount[]>
497
452
 
498
453
  ### Constants
499
454
 
455
+ #### `create`
456
+
457
+ Create an article from a flat body as the session user.
458
+
459
+ ```typescript
460
+ const create: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
461
+ ```
462
+
463
+ #### `list`
464
+
465
+ List articles with the standard filters and pagination envelope.
466
+
467
+ ```typescript
468
+ const list: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
469
+ ```
470
+
471
+ #### `feed`
472
+
473
+ List articles by followed authors for the session user.
474
+
475
+ ```typescript
476
+ const feed: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
477
+ ```
478
+
479
+ #### `tags`
480
+
481
+ Return tags in use, optionally capped by the requested limit.
482
+
483
+ ```typescript
484
+ const tags: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
485
+ ```
486
+
487
+ #### `read`
488
+
489
+ Read an article by slug, including the viewer's favorite state.
490
+
491
+ ```typescript
492
+ const read: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
493
+ ```
494
+
495
+ #### `update`
496
+
497
+ Update an article as its author.
498
+
499
+ ```typescript
500
+ const update: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
501
+ ```
502
+
503
+ #### `del`
504
+
505
+ Delete an article as its author, returning an empty 204.
506
+
507
+ ```typescript
508
+ const del: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
509
+ ```
510
+
500
511
  #### `favorite`
501
512
 
502
- `POST /articles/:slug/favorite` — idempotent; returns the article.
513
+ Favorite an article as the session user.
503
514
 
504
515
  ```typescript
505
516
  const favorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
@@ -507,7 +518,7 @@ const favorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
507
518
 
508
519
  #### `unfavorite`
509
520
 
510
- `DELETE /articles/:slug/favorite` — idempotent; returns the article.
521
+ Unfavorite an article as the session user.
511
522
 
512
523
  ```typescript
513
524
  const unfavorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
@@ -519,13 +530,13 @@ Handler map for article routes.
519
530
 
520
531
  ```typescript
521
532
  const requestHandlerMap: {
522
- readonly create: typeof create
523
- readonly list: typeof list
524
- readonly feed: typeof feed
525
- readonly tags: typeof tags
526
- readonly read: typeof read
527
- readonly update: typeof update
528
- readonly del: typeof del
533
+ readonly create: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
534
+ readonly list: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
535
+ readonly feed: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
536
+ readonly tags: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
537
+ readonly read: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
538
+ readonly update: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
539
+ readonly del: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
529
540
  readonly favorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
530
541
  readonly unfavorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
531
542
  }
@@ -653,7 +664,7 @@ Peer dependencies:
653
664
  - `@molecule/api-database` ^1.0.1
654
665
  - `@molecule/api-i18n` ^1.0.1
655
666
  - `@molecule/api-logger` ^1.0.1
656
- - `@molecule/api-resource` ^1.0.1
667
+ - `@molecule/api-resource` ^1.1.0
657
668
  - `@molecule/api-resource-follow` ^1.0.5
658
669
  - `@molecule/api-resource-reaction` ^1.0.3
659
670
  - `@molecule/api-slug` ^1.0.0
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Article HTTP handlers with optional per-project wire-format mappings.
3
+ *
4
+ * @module
5
+ */
6
+ import { type MoleculeRequest, type MoleculeResponse, type RequestHandlerOptions } from '@molecule/api-resource';
7
+ import * as operations from './operations.js';
8
+ /** HTTP handlers for all article routes. Authorization stays in each operation. */
9
+ export type ArticleRequestHandlerMap = {
10
+ [Name in keyof typeof operations]: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
11
+ };
12
+ /**
13
+ * Create article handlers for this project's wire format. Adapt an envelope,
14
+ * filter names or response projection without rewriting the article operations.
15
+ * Each mapping receives the adapted request and its original response context.
16
+ * Omit the options for the standard flat-body, raw-article and paginated-list API.
17
+ * Error and partial responses reach mapResponse too, so preserve them explicitly.
18
+ *
19
+ * @param options - Shared resource request/response mappings, scoped to this map.
20
+ * @returns A route-compatible map with the same names as requestHandlerMap.
21
+ */
22
+ export declare const createArticleHandlers: (options?: RequestHandlerOptions) => ArticleRequestHandlerMap;
23
+ /** Create an article from a flat body as the session user. */
24
+ export declare const create: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
25
+ /** List articles with the standard filters and pagination envelope. */
26
+ export declare const list: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
27
+ /** List articles by followed authors for the session user. */
28
+ export declare const feed: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
29
+ /** Return tags in use, optionally capped by the requested limit. */
30
+ export declare const tags: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
31
+ /** Read an article by slug, including the viewer's favorite state. */
32
+ export declare const read: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
33
+ /** Update an article as its author. */
34
+ export declare const update: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
35
+ /** Delete an article as its author, returning an empty 204. */
36
+ export declare const del: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
37
+ /** Favorite an article as the session user. */
38
+ export declare const favorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
39
+ /** Unfavorite an article as the session user. */
40
+ export declare const unfavorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
41
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/handlers/http.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAC3B,MAAM,wBAAwB,CAAA;AAE/B,OAAO,KAAK,UAAU,MAAM,iBAAiB,CAAA;AAG7C,mFAAmF;AACnF,MAAM,MAAM,wBAAwB,GAAG;KACpC,IAAI,IAAI,MAAM,OAAO,UAAU,GAAG,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAAC;CAClG,CAAA;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,GAChC,UAAS,qBAA0B,KAClC,wBA8BF,CAAA;AAMD,8DAA8D;AAC9D,eAAO,MAAM,MAAM,QApDwB,eAAe,OAAO,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAoD7D,CAAA;AACrC,uEAAuE;AACvE,eAAO,MAAM,IAAI,QAtD0B,eAAe,OAAO,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAsDjE,CAAA;AACjC,8DAA8D;AAC9D,eAAO,MAAM,IAAI,QAxD0B,eAAe,OAAO,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAwDjE,CAAA;AACjC,oEAAoE;AACpE,eAAO,MAAM,IAAI,QA1D0B,eAAe,OAAO,gBAAgB,KAAK,OAAO,CAAC,IAAI,CA0DjE,CAAA;AACjC,sEAAsE;AACtE,eAAO,MAAM,IAAI,QA5D0B,eAAe,OAAO,gBAAgB,KAAK,OAAO,CAAC,IAAI,CA4DjE,CAAA;AACjC,uCAAuC;AACvC,eAAO,MAAM,MAAM,QA9DwB,eAAe,OAAO,gBAAgB,KAAK,OAAO,CAAC,IAAI,CA8D7D,CAAA;AACrC,+DAA+D;AAC/D,eAAO,MAAM,GAAG,QAhE2B,eAAe,OAAO,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAgEnE,CAAA;AAC/B,+CAA+C;AAC/C,eAAO,MAAM,QAAQ,QAlEsB,eAAe,OAAO,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAkEzD,CAAA;AACzC,iDAAiD;AACjD,eAAO,MAAM,UAAU,QApEoB,eAAe,OAAO,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAoErD,CAAA"}
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Article HTTP handlers with optional per-project wire-format mappings.
3
+ *
4
+ * @module
5
+ */
6
+ import { logger } from '@molecule/api-logger';
7
+ import { adaptHandler, } from '@molecule/api-resource';
8
+ import * as operations from './operations.js';
9
+ import { failed } from './shared.js';
10
+ /**
11
+ * Create article handlers for this project's wire format. Adapt an envelope,
12
+ * filter names or response projection without rewriting the article operations.
13
+ * Each mapping receives the adapted request and its original response context.
14
+ * Omit the options for the standard flat-body, raw-article and paginated-list API.
15
+ * Error and partial responses reach mapResponse too, so preserve them explicitly.
16
+ *
17
+ * @param options - Shared resource request/response mappings, scoped to this map.
18
+ * @returns A route-compatible map with the same names as requestHandlerMap.
19
+ */
20
+ export const createArticleHandlers = (options = {}) => {
21
+ const wrap = (operation) => {
22
+ const handler = adaptHandler(operations[operation], options);
23
+ return async (req, res) => {
24
+ try {
25
+ const result = await handler(req, res);
26
+ // Article operations always return a response; no route falls through.
27
+ if (!result)
28
+ throw new Error(`Article operation ${operation} returned no response`);
29
+ if (result.headers)
30
+ res.set(result.headers);
31
+ res.status(result.statusCode);
32
+ if (result.statusCode === 204 || result.statusCode === 304)
33
+ res.end();
34
+ else
35
+ res.json(result.body);
36
+ }
37
+ catch (error) {
38
+ logger.error('Failed to adapt article response', { operation, error });
39
+ const result = failed('resource.error.unknownError', 'Something went wrong.');
40
+ res.status(result.statusCode).json(result.body);
41
+ }
42
+ };
43
+ };
44
+ return {
45
+ create: wrap('create'),
46
+ list: wrap('list'),
47
+ feed: wrap('feed'),
48
+ tags: wrap('tags'),
49
+ read: wrap('read'),
50
+ update: wrap('update'),
51
+ del: wrap('del'),
52
+ favorite: wrap('favorite'),
53
+ unfavorite: wrap('unfavorite'),
54
+ };
55
+ };
56
+ const defaults = createArticleHandlers();
57
+ /** Create an article from a flat body as the session user. */
58
+ export const create = defaults.create;
59
+ /** List articles with the standard filters and pagination envelope. */
60
+ export const list = defaults.list;
61
+ /** List articles by followed authors for the session user. */
62
+ export const feed = defaults.feed;
63
+ /** Return tags in use, optionally capped by the requested limit. */
64
+ export const tags = defaults.tags;
65
+ /** Read an article by slug, including the viewer's favorite state. */
66
+ export const read = defaults.read;
67
+ /** Update an article as its author. */
68
+ export const update = defaults.update;
69
+ /** Delete an article as its author, returning an empty 204. */
70
+ export const del = defaults.del;
71
+ /** Favorite an article as the session user. */
72
+ export const favorite = defaults.favorite;
73
+ /** Unfavorite an article as the session user. */
74
+ export const unfavorite = defaults.unfavorite;
@@ -1,64 +1,7 @@
1
1
  /**
2
- * Article route handlers.
2
+ * Article HTTP handlers and their configurable factory.
3
3
  *
4
4
  * @module
5
5
  */
6
- import type { MoleculeRequest, MoleculeResponse } from '@molecule/api-resource';
7
- /**
8
- * `POST /articles` — create an article as the signed-in user.
9
- *
10
- * @param req - Body: `{ title, body, description?, tagList? }`.
11
- * @param res - 201 with the article.
12
- */
13
- export declare function create(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
14
- /**
15
- * `GET /articles` — newest first; `?tag=`, `?author=` (user id),
16
- * `?favoritedBy=` (user id), `?limit=`, `?offset=`.
17
- *
18
- * @param req - The request.
19
- * @param res - `{ data, total, limit, offset }`.
20
- */
21
- export declare function list(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
22
- /**
23
- * `GET /articles/feed` — articles by the authors the signed-in user follows.
24
- *
25
- * @param req - `?limit=`, `?offset=`.
26
- * @param res - `{ data, total, limit, offset }`.
27
- */
28
- export declare function feed(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
29
- /**
30
- * `GET /articles/tags` — every tag in use, most-used first.
31
- *
32
- * With no `?limit=` this is the whole list, the shape RealWorld's `GET /tags`
33
- * asks for; `?limit=` narrows it to that many most-used tags.
34
- *
35
- * @param req - The request; `?limit=` caps the list.
36
- * @param res - `[{ tag, count }]`.
37
- */
38
- export declare function tags(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
39
- /**
40
- * `GET /articles/:slug`.
41
- *
42
- * @param req - The request.
43
- * @param res - The article, or 404.
44
- */
45
- export declare function read(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
46
- /**
47
- * `PUT /articles/:slug` — author only; a new title gives a new slug.
48
- *
49
- * @param req - Body: any of `{ title, description, body, tagList }`.
50
- * @param res - The updated article, 403 or 404.
51
- */
52
- export declare function update(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
53
- /**
54
- * `DELETE /articles/:slug` — author only.
55
- *
56
- * @param req - The request.
57
- * @param res - 204, 403 or 404.
58
- */
59
- export declare function del(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
60
- /** `POST /articles/:slug/favorite` — idempotent; returns the article. */
61
- export declare const favorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
62
- /** `DELETE /articles/:slug/favorite` — idempotent; returns the article. */
63
- export declare const unfavorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
6
+ export * from './http.js';
64
7
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/handlers/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAyB/E;;;;;GAKG;AACH,wBAAsB,MAAM,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAWvF;AAED;;;;;;GAMG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBrF;AAED;;;;;GAKG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAcrF;AAED;;;;;;;;GAQG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAQrF;AAED;;;;;GAKG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CASrF;AAED;;;;;GAKG;AACH,wBAAsB,MAAM,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAcvF;AAED;;;;;GAKG;AACH,wBAAsB,GAAG,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAYpF;AAiBD,yEAAyE;AACzE,eAAO,MAAM,QAAQ,QAdP,eAAe,OAAO,gBAAgB,KAAG,OAAO,CAAC,IAAI,CActB,CAAA;AAE7C,2EAA2E;AAC3E,eAAO,MAAM,UAAU,QAjBT,eAAe,OAAO,gBAAgB,KAAG,OAAO,CAAC,IAAI,CAiBnB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/handlers/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,cAAc,WAAW,CAAA"}
@@ -1,179 +1,6 @@
1
1
  /**
2
- * Article route handlers.
2
+ * Article HTTP handlers and their configurable factory.
3
3
  *
4
4
  * @module
5
5
  */
6
- import { logger } from '@molecule/api-logger';
7
- import { allTags, createArticle, deleteArticle, getArticleBySlug, getFeed, listArticles, popularTags, setFavorite, updateArticle, } from '../service.js';
8
- import { createArticleSchema, updateArticleSchema } from '../validation.js';
9
- import { failed, forbidden, invalid, notFound, queryInt, queryString, sessionUserId, unauthorized, } from './shared.js';
10
- /**
11
- * `POST /articles` — create an article as the signed-in user.
12
- *
13
- * @param req - Body: `{ title, body, description?, tagList? }`.
14
- * @param res - 201 with the article.
15
- */
16
- export async function create(req, res) {
17
- const userId = sessionUserId(res);
18
- if (!userId)
19
- return unauthorized(res);
20
- const parsed = createArticleSchema.safeParse(req.body);
21
- if (!parsed.success)
22
- return invalid(res, parsed.error.issues);
23
- try {
24
- res.status(201).json(await createArticle(userId, parsed.data));
25
- }
26
- catch (error) {
27
- logger.error('Failed to create article', { userId, error });
28
- failed(res, 'article.error.createFailed', 'Failed to create article');
29
- }
30
- }
31
- /**
32
- * `GET /articles` — newest first; `?tag=`, `?author=` (user id),
33
- * `?favoritedBy=` (user id), `?limit=`, `?offset=`.
34
- *
35
- * @param req - The request.
36
- * @param res - `{ data, total, limit, offset }`.
37
- */
38
- export async function list(req, res) {
39
- try {
40
- res.json(await listArticles({
41
- tag: queryString(req.query.tag),
42
- authorId: queryString(req.query.author),
43
- favoritedBy: queryString(req.query.favoritedBy),
44
- limit: queryInt(req.query.limit),
45
- offset: queryInt(req.query.offset),
46
- viewerId: sessionUserId(res),
47
- }));
48
- }
49
- catch (error) {
50
- logger.error('Failed to list articles', { error });
51
- failed(res, 'article.error.listFailed', 'Failed to list articles');
52
- }
53
- }
54
- /**
55
- * `GET /articles/feed` — articles by the authors the signed-in user follows.
56
- *
57
- * @param req - `?limit=`, `?offset=`.
58
- * @param res - `{ data, total, limit, offset }`.
59
- */
60
- export async function feed(req, res) {
61
- const userId = sessionUserId(res);
62
- if (!userId)
63
- return unauthorized(res);
64
- try {
65
- res.json(await getFeed(userId, {
66
- limit: queryInt(req.query.limit),
67
- offset: queryInt(req.query.offset),
68
- }));
69
- }
70
- catch (error) {
71
- logger.error('Failed to read the article feed', { userId, error });
72
- failed(res, 'article.error.feedFailed', 'Failed to load the feed');
73
- }
74
- }
75
- /**
76
- * `GET /articles/tags` — every tag in use, most-used first.
77
- *
78
- * With no `?limit=` this is the whole list, the shape RealWorld's `GET /tags`
79
- * asks for; `?limit=` narrows it to that many most-used tags.
80
- *
81
- * @param req - The request; `?limit=` caps the list.
82
- * @param res - `[{ tag, count }]`.
83
- */
84
- export async function tags(req, res) {
85
- try {
86
- const limit = queryInt(req.query.limit);
87
- res.json(limit === undefined ? await allTags() : await popularTags(limit));
88
- }
89
- catch (error) {
90
- logger.error('Failed to list article tags', { error });
91
- failed(res, 'article.error.tagsFailed', 'Failed to list tags');
92
- }
93
- }
94
- /**
95
- * `GET /articles/:slug`.
96
- *
97
- * @param req - The request.
98
- * @param res - The article, or 404.
99
- */
100
- export async function read(req, res) {
101
- try {
102
- const article = await getArticleBySlug(String(req.params.slug), sessionUserId(res));
103
- if (!article)
104
- return notFound(res);
105
- res.json(article);
106
- }
107
- catch (error) {
108
- logger.error('Failed to read article', { slug: req.params.slug, error });
109
- failed(res, 'article.error.readFailed', 'Failed to load the article');
110
- }
111
- }
112
- /**
113
- * `PUT /articles/:slug` — author only; a new title gives a new slug.
114
- *
115
- * @param req - Body: any of `{ title, description, body, tagList }`.
116
- * @param res - The updated article, 403 or 404.
117
- */
118
- export async function update(req, res) {
119
- const userId = sessionUserId(res);
120
- if (!userId)
121
- return unauthorized(res);
122
- const parsed = updateArticleSchema.safeParse(req.body);
123
- if (!parsed.success)
124
- return invalid(res, parsed.error.issues);
125
- try {
126
- const result = await updateArticle(String(req.params.slug), userId, parsed.data);
127
- if (result.status === 'not_found')
128
- return notFound(res);
129
- if (result.status === 'forbidden')
130
- return forbidden(res);
131
- res.json(result.article);
132
- }
133
- catch (error) {
134
- logger.error('Failed to update article', { slug: req.params.slug, userId, error });
135
- failed(res, 'article.error.updateFailed', 'Failed to update article');
136
- }
137
- }
138
- /**
139
- * `DELETE /articles/:slug` — author only.
140
- *
141
- * @param req - The request.
142
- * @param res - 204, 403 or 404.
143
- */
144
- export async function del(req, res) {
145
- const userId = sessionUserId(res);
146
- if (!userId)
147
- return unauthorized(res);
148
- try {
149
- const result = await deleteArticle(String(req.params.slug), userId);
150
- if (result.status === 'not_found')
151
- return notFound(res);
152
- if (result.status === 'forbidden')
153
- return forbidden(res);
154
- res.status(204).end();
155
- }
156
- catch (error) {
157
- logger.error('Failed to delete article', { slug: req.params.slug, userId, error });
158
- failed(res, 'article.error.deleteFailed', 'Failed to delete article');
159
- }
160
- }
161
- const favoriteHandler = (on) => async (req, res) => {
162
- const userId = sessionUserId(res);
163
- if (!userId)
164
- return unauthorized(res);
165
- try {
166
- const article = await setFavorite(String(req.params.slug), userId, on);
167
- if (!article)
168
- return notFound(res);
169
- res.json(article);
170
- }
171
- catch (error) {
172
- logger.error('Failed to change an article favorite', { slug: req.params.slug, userId, error });
173
- failed(res, 'article.error.favoriteFailed', 'Failed to update the favorite');
174
- }
175
- };
176
- /** `POST /articles/:slug/favorite` — idempotent; returns the article. */
177
- export const favorite = favoriteHandler(true);
178
- /** `DELETE /articles/:slug/favorite` — idempotent; returns the article. */
179
- export const unfavorite = favoriteHandler(false);
6
+ export * from './http.js';
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Structured article operations, before HTTP wire-format adaptation.
3
+ *
4
+ * @module
5
+ */
6
+ import type { MoleculeRequest, MoleculeResponse, Response } from '@molecule/api-resource';
7
+ /**
8
+ * `POST /articles` — create an article as the signed-in user.
9
+ *
10
+ * @param req - Body: `{ title, body, description?, tagList? }`.
11
+ * @param res - The response context containing the session.
12
+ * @returns The created article or a structured error response.
13
+ */
14
+ export declare function create(req: MoleculeRequest, res: MoleculeResponse): Promise<Response>;
15
+ /**
16
+ * `GET /articles` — newest first; `?tag=`, `?author=` (user id),
17
+ * `?favoritedBy=` (user id), `?limit=`, `?offset=`.
18
+ *
19
+ * @param req - The request.
20
+ * @param res - The response context containing the viewer.
21
+ * @returns A structured page or error response.
22
+ */
23
+ export declare function list(req: MoleculeRequest, res: MoleculeResponse): Promise<Response>;
24
+ /**
25
+ * `GET /articles/feed` — articles by the authors the signed-in user follows.
26
+ *
27
+ * @param req - `?limit=`, `?offset=`.
28
+ * @param res - The response context containing the viewer.
29
+ * @returns A structured page or error response.
30
+ */
31
+ export declare function feed(req: MoleculeRequest, res: MoleculeResponse): Promise<Response>;
32
+ /**
33
+ * `GET /articles/tags` — every tag in use, most-used first.
34
+ *
35
+ * With no `?limit=` this is the whole list, the shape RealWorld's `GET /tags`
36
+ * asks for; `?limit=` narrows it to that many most-used tags.
37
+ *
38
+ * @param req - The request; `?limit=` caps the list.
39
+ * @param _res - The unused response context.
40
+ * @returns A structured tag list or error response.
41
+ */
42
+ export declare function tags(req: MoleculeRequest, _res: MoleculeResponse): Promise<Response>;
43
+ /**
44
+ * `GET /articles/:slug`.
45
+ *
46
+ * @param req - The request.
47
+ * @param res - The response context containing the viewer.
48
+ * @returns A structured article or not-found/error response.
49
+ */
50
+ export declare function read(req: MoleculeRequest, res: MoleculeResponse): Promise<Response>;
51
+ /**
52
+ * `PUT /articles/:slug` — author only; a new title gives a new slug.
53
+ *
54
+ * @param req - Body: any of `{ title, description, body, tagList }`.
55
+ * @param res - The response context containing the session.
56
+ * @returns The updated article or a structured permission/not-found/error response.
57
+ */
58
+ export declare function update(req: MoleculeRequest, res: MoleculeResponse): Promise<Response>;
59
+ /**
60
+ * `DELETE /articles/:slug` — author only.
61
+ *
62
+ * @param req - The request.
63
+ * @param res - The response context containing the session.
64
+ * @returns A structured empty success or permission/not-found/error response.
65
+ */
66
+ export declare function del(req: MoleculeRequest, res: MoleculeResponse): Promise<Response>;
67
+ /** `POST /articles/:slug/favorite` — idempotent; returns the article. */
68
+ export declare const favorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<Response>;
69
+ /** `DELETE /articles/:slug/favorite` — idempotent; returns the article. */
70
+ export declare const unfavorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<Response>;
71
+ //# sourceMappingURL=operations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"operations.d.ts","sourceRoot":"","sources":["../../src/handlers/operations.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAA;AAyBzF;;;;;;GAMG;AACH,wBAAsB,MAAM,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAW3F;AAED;;;;;;;GAOG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiBzF;AAED;;;;;;GAMG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAezF;AAED;;;;;;;;;GASG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,IAAI,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAW1F;AAED;;;;;;GAMG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CASzF;AAED;;;;;;GAMG;AACH,wBAAsB,MAAM,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAc3F;AAED;;;;;;GAMG;AACH,wBAAsB,GAAG,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAYxF;AAiBD,yEAAyE;AACzE,eAAO,MAAM,QAAQ,QAdP,eAAe,OAAO,gBAAgB,KAAG,OAAO,CAAC,QAAQ,CAc1B,CAAA;AAE7C,2EAA2E;AAC3E,eAAO,MAAM,UAAU,QAjBT,eAAe,OAAO,gBAAgB,KAAG,OAAO,CAAC,QAAQ,CAiBvB,CAAA"}
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Structured article operations, before HTTP wire-format adaptation.
3
+ *
4
+ * @module
5
+ */
6
+ import { logger } from '@molecule/api-logger';
7
+ import { allTags, createArticle, deleteArticle, getArticleBySlug, getFeed, listArticles, popularTags, setFavorite, updateArticle, } from '../service.js';
8
+ import { createArticleSchema, updateArticleSchema } from '../validation.js';
9
+ import { failed, forbidden, invalid, notFound, queryInt, queryString, sessionUserId, unauthorized, } from './shared.js';
10
+ /**
11
+ * `POST /articles` — create an article as the signed-in user.
12
+ *
13
+ * @param req - Body: `{ title, body, description?, tagList? }`.
14
+ * @param res - The response context containing the session.
15
+ * @returns The created article or a structured error response.
16
+ */
17
+ export async function create(req, res) {
18
+ const userId = sessionUserId(res);
19
+ if (!userId)
20
+ return unauthorized();
21
+ const parsed = createArticleSchema.safeParse(req.body);
22
+ if (!parsed.success)
23
+ return invalid(parsed.error.issues);
24
+ try {
25
+ return { statusCode: 201, body: await createArticle(userId, parsed.data) };
26
+ }
27
+ catch (error) {
28
+ logger.error('Failed to create article', { userId, error });
29
+ return failed('article.error.createFailed', 'Failed to create article');
30
+ }
31
+ }
32
+ /**
33
+ * `GET /articles` — newest first; `?tag=`, `?author=` (user id),
34
+ * `?favoritedBy=` (user id), `?limit=`, `?offset=`.
35
+ *
36
+ * @param req - The request.
37
+ * @param res - The response context containing the viewer.
38
+ * @returns A structured page or error response.
39
+ */
40
+ export async function list(req, res) {
41
+ try {
42
+ return {
43
+ statusCode: 200,
44
+ body: await listArticles({
45
+ tag: queryString(req.query.tag),
46
+ authorId: queryString(req.query.author),
47
+ favoritedBy: queryString(req.query.favoritedBy),
48
+ limit: queryInt(req.query.limit),
49
+ offset: queryInt(req.query.offset),
50
+ viewerId: sessionUserId(res),
51
+ }),
52
+ };
53
+ }
54
+ catch (error) {
55
+ logger.error('Failed to list articles', { error });
56
+ return failed('article.error.listFailed', 'Failed to list articles');
57
+ }
58
+ }
59
+ /**
60
+ * `GET /articles/feed` — articles by the authors the signed-in user follows.
61
+ *
62
+ * @param req - `?limit=`, `?offset=`.
63
+ * @param res - The response context containing the viewer.
64
+ * @returns A structured page or error response.
65
+ */
66
+ export async function feed(req, res) {
67
+ const userId = sessionUserId(res);
68
+ if (!userId)
69
+ return unauthorized();
70
+ try {
71
+ return {
72
+ statusCode: 200,
73
+ body: await getFeed(userId, {
74
+ limit: queryInt(req.query.limit),
75
+ offset: queryInt(req.query.offset),
76
+ }),
77
+ };
78
+ }
79
+ catch (error) {
80
+ logger.error('Failed to read the article feed', { userId, error });
81
+ return failed('article.error.feedFailed', 'Failed to load the feed');
82
+ }
83
+ }
84
+ /**
85
+ * `GET /articles/tags` — every tag in use, most-used first.
86
+ *
87
+ * With no `?limit=` this is the whole list, the shape RealWorld's `GET /tags`
88
+ * asks for; `?limit=` narrows it to that many most-used tags.
89
+ *
90
+ * @param req - The request; `?limit=` caps the list.
91
+ * @param _res - The unused response context.
92
+ * @returns A structured tag list or error response.
93
+ */
94
+ export async function tags(req, _res) {
95
+ try {
96
+ const limit = queryInt(req.query.limit);
97
+ return {
98
+ statusCode: 200,
99
+ body: limit === undefined ? await allTags() : await popularTags(limit),
100
+ };
101
+ }
102
+ catch (error) {
103
+ logger.error('Failed to list article tags', { error });
104
+ return failed('article.error.tagsFailed', 'Failed to list tags');
105
+ }
106
+ }
107
+ /**
108
+ * `GET /articles/:slug`.
109
+ *
110
+ * @param req - The request.
111
+ * @param res - The response context containing the viewer.
112
+ * @returns A structured article or not-found/error response.
113
+ */
114
+ export async function read(req, res) {
115
+ try {
116
+ const article = await getArticleBySlug(String(req.params.slug), sessionUserId(res));
117
+ if (!article)
118
+ return notFound();
119
+ return { statusCode: 200, body: article };
120
+ }
121
+ catch (error) {
122
+ logger.error('Failed to read article', { slug: req.params.slug, error });
123
+ return failed('article.error.readFailed', 'Failed to load the article');
124
+ }
125
+ }
126
+ /**
127
+ * `PUT /articles/:slug` — author only; a new title gives a new slug.
128
+ *
129
+ * @param req - Body: any of `{ title, description, body, tagList }`.
130
+ * @param res - The response context containing the session.
131
+ * @returns The updated article or a structured permission/not-found/error response.
132
+ */
133
+ export async function update(req, res) {
134
+ const userId = sessionUserId(res);
135
+ if (!userId)
136
+ return unauthorized();
137
+ const parsed = updateArticleSchema.safeParse(req.body);
138
+ if (!parsed.success)
139
+ return invalid(parsed.error.issues);
140
+ try {
141
+ const result = await updateArticle(String(req.params.slug), userId, parsed.data);
142
+ if (result.status === 'not_found')
143
+ return notFound();
144
+ if (result.status === 'forbidden')
145
+ return forbidden();
146
+ return { statusCode: 200, body: result.article };
147
+ }
148
+ catch (error) {
149
+ logger.error('Failed to update article', { slug: req.params.slug, userId, error });
150
+ return failed('article.error.updateFailed', 'Failed to update article');
151
+ }
152
+ }
153
+ /**
154
+ * `DELETE /articles/:slug` — author only.
155
+ *
156
+ * @param req - The request.
157
+ * @param res - The response context containing the session.
158
+ * @returns A structured empty success or permission/not-found/error response.
159
+ */
160
+ export async function del(req, res) {
161
+ const userId = sessionUserId(res);
162
+ if (!userId)
163
+ return unauthorized();
164
+ try {
165
+ const result = await deleteArticle(String(req.params.slug), userId);
166
+ if (result.status === 'not_found')
167
+ return notFound();
168
+ if (result.status === 'forbidden')
169
+ return forbidden();
170
+ return { statusCode: 204, body: undefined };
171
+ }
172
+ catch (error) {
173
+ logger.error('Failed to delete article', { slug: req.params.slug, userId, error });
174
+ return failed('article.error.deleteFailed', 'Failed to delete article');
175
+ }
176
+ }
177
+ const favoriteHandler = (on) => async (req, res) => {
178
+ const userId = sessionUserId(res);
179
+ if (!userId)
180
+ return unauthorized();
181
+ try {
182
+ const article = await setFavorite(String(req.params.slug), userId, on);
183
+ if (!article)
184
+ return notFound();
185
+ return { statusCode: 200, body: article };
186
+ }
187
+ catch (error) {
188
+ logger.error('Failed to change an article favorite', { slug: req.params.slug, userId, error });
189
+ return failed('article.error.favoriteFailed', 'Failed to update the favorite');
190
+ }
191
+ };
192
+ /** `POST /articles/:slug/favorite` — idempotent; returns the article. */
193
+ export const favorite = favoriteHandler(true);
194
+ /** `DELETE /articles/:slug/favorite` — idempotent; returns the article. */
195
+ export const unfavorite = favoriteHandler(false);
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- import type { MoleculeResponse } from '@molecule/api-resource';
6
+ import type { MoleculeResponse, Response } from '@molecule/api-resource';
7
7
  /**
8
8
  * The signed-in user's id, if any.
9
9
  *
@@ -14,39 +14,39 @@ export declare const sessionUserId: (res: MoleculeResponse) => string | undefine
14
14
  /**
15
15
  * Answer 401.
16
16
  *
17
- * @param res - The response.
17
+ * @returns The structured unauthorized response.
18
18
  */
19
- export declare const unauthorized: (res: MoleculeResponse) => void;
19
+ export declare const unauthorized: () => Response;
20
20
  /**
21
21
  * Answer 404 for a missing article.
22
22
  *
23
- * @param res - The response.
23
+ * @returns The structured not-found response.
24
24
  */
25
- export declare const notFound: (res: MoleculeResponse) => void;
25
+ export declare const notFound: () => Response;
26
26
  /**
27
27
  * Answer 403 for a change only the author may make.
28
28
  *
29
- * @param res - The response.
29
+ * @returns The structured forbidden response.
30
30
  */
31
- export declare const forbidden: (res: MoleculeResponse) => void;
31
+ export declare const forbidden: () => Response;
32
32
  /**
33
33
  * Answer 500 after logging.
34
34
  *
35
- * @param res - The response.
36
35
  * @param key - The i18n key (`article.error.*`).
37
36
  * @param fallback - The English message.
37
+ * @returns The structured failure response.
38
38
  */
39
- export declare const failed: (res: MoleculeResponse, key: string, fallback: string) => void;
39
+ export declare const failed: (key: string, fallback: string) => Response;
40
40
  /**
41
41
  * Answer 400 for input that failed validation.
42
42
  *
43
- * @param res - The response.
44
43
  * @param issues - The schema's issues.
44
+ * @returns The structured validation response.
45
45
  */
46
- export declare const invalid: (res: MoleculeResponse, issues: ReadonlyArray<{
46
+ export declare const invalid: (issues: ReadonlyArray<{
47
47
  path: PropertyKey[];
48
48
  message: string;
49
- }>) => void;
49
+ }>) => Response;
50
50
  /**
51
51
  * A query-string number, or undefined.
52
52
  *
@@ -1 +1 @@
1
- {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/handlers/shared.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAE9D;;;;;GAKG;AACH,eAAO,MAAM,aAAa,GAAI,KAAK,gBAAgB,KAAG,MAAM,GAAG,SACE,CAAA;AAEjE;;;;GAIG;AACH,eAAO,MAAM,YAAY,GAAI,KAAK,gBAAgB,KAAG,IAKpD,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,QAAQ,GAAI,KAAK,gBAAgB,KAAG,IAKhD,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,SAAS,GAAI,KAAK,gBAAgB,KAAG,IAOjD,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,MAAM,GAAI,KAAK,gBAAgB,EAAE,KAAK,MAAM,EAAE,UAAU,MAAM,KAAG,IAE7E,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,OAAO,GAClB,KAAK,gBAAgB,EACrB,QAAQ,aAAa,CAAC;IAAE,IAAI,EAAE,WAAW,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,KAC9D,IAKF,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,QAAQ,GAAI,OAAO,OAAO,KAAG,MAAM,GAAG,SAGlD,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,WAAW,GAAI,OAAO,OAAO,KAAG,MAAM,GAAG,SACgB,CAAA"}
1
+ {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/handlers/shared.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAA;AAExE;;;;;GAKG;AACH,eAAO,MAAM,aAAa,GAAI,KAAK,gBAAgB,KAAG,MAAM,GAAG,SACE,CAAA;AAEjE;;;;GAIG;AACH,eAAO,MAAM,YAAY,QAAO,QAM9B,CAAA;AAEF;;;;GAIG;AACH,eAAO,MAAM,QAAQ,QAAO,QAM1B,CAAA;AAEF;;;;GAIG;AACH,eAAO,MAAM,SAAS,QAAO,QAQ3B,CAAA;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,MAAM,GAAI,KAAK,MAAM,EAAE,UAAU,MAAM,KAAG,QAGrD,CAAA;AAEF;;;;;GAKG;AACH,eAAO,MAAM,OAAO,GAClB,QAAQ,aAAa,CAAC;IAAE,IAAI,EAAE,WAAW,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,KAC9D,QAMD,CAAA;AAEF;;;;;GAKG;AACH,eAAO,MAAM,QAAQ,GAAI,OAAO,OAAO,KAAG,MAAM,GAAG,SAGlD,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,WAAW,GAAI,OAAO,OAAO,KAAG,MAAM,GAAG,SACgB,CAAA"}
@@ -14,60 +14,65 @@ export const sessionUserId = (res) => res.locals.session?.userId;
14
14
  /**
15
15
  * Answer 401.
16
16
  *
17
- * @param res - The response.
17
+ * @returns The structured unauthorized response.
18
18
  */
19
- export const unauthorized = (res) => {
20
- res.status(401).json({
19
+ export const unauthorized = () => ({
20
+ statusCode: 401,
21
+ body: {
21
22
  error: t('resource.error.unauthorized', undefined, { defaultValue: 'Unauthorized' }),
22
23
  errorKey: 'resource.error.unauthorized',
23
- });
24
- };
24
+ },
25
+ });
25
26
  /**
26
27
  * Answer 404 for a missing article.
27
28
  *
28
- * @param res - The response.
29
+ * @returns The structured not-found response.
29
30
  */
30
- export const notFound = (res) => {
31
- res.status(404).json({
31
+ export const notFound = () => ({
32
+ statusCode: 404,
33
+ body: {
32
34
  error: t('article.error.notFound', undefined, { defaultValue: 'Article not found' }),
33
35
  errorKey: 'article.error.notFound',
34
- });
35
- };
36
+ },
37
+ });
36
38
  /**
37
39
  * Answer 403 for a change only the author may make.
38
40
  *
39
- * @param res - The response.
41
+ * @returns The structured forbidden response.
40
42
  */
41
- export const forbidden = (res) => {
42
- res.status(403).json({
43
+ export const forbidden = () => ({
44
+ statusCode: 403,
45
+ body: {
43
46
  error: t('article.error.notAuthor', undefined, {
44
47
  defaultValue: 'Only the author can change this article',
45
48
  }),
46
49
  errorKey: 'article.error.notAuthor',
47
- });
48
- };
50
+ },
51
+ });
49
52
  /**
50
53
  * Answer 500 after logging.
51
54
  *
52
- * @param res - The response.
53
55
  * @param key - The i18n key (`article.error.*`).
54
56
  * @param fallback - The English message.
57
+ * @returns The structured failure response.
55
58
  */
56
- export const failed = (res, key, fallback) => {
57
- res.status(500).json({ error: t(key, undefined, { defaultValue: fallback }), errorKey: key });
58
- };
59
+ export const failed = (key, fallback) => ({
60
+ statusCode: 500,
61
+ body: { error: t(key, undefined, { defaultValue: fallback }), errorKey: key },
62
+ });
59
63
  /**
60
64
  * Answer 400 for input that failed validation.
61
65
  *
62
- * @param res - The response.
63
66
  * @param issues - The schema's issues.
67
+ * @returns The structured validation response.
64
68
  */
65
- export const invalid = (res, issues) => {
66
- res.status(400).json({
69
+ export const invalid = (issues) => ({
70
+ statusCode: 400,
71
+ body: {
67
72
  error: issues.map((e) => `${e.path.map(String).join('.')}: ${e.message}`).join(', '),
68
73
  errorKey: 'article.error.validationFailed',
69
- });
70
- };
74
+ },
75
+ });
71
76
  /**
72
77
  * A query-string number, or undefined.
73
78
  *
package/dist/index.d.ts CHANGED
@@ -32,17 +32,27 @@
32
32
  *
33
33
  * @example
34
34
  * ```typescript
35
- * // An API with its own response shape (a spec you must match) uses the
36
- * // service and writes its own envelope:
37
- * import { createArticle, listArticles } from '@molecule/api-resource-article'
35
+ * // Configure a publishing API's envelopes without rewriting its operations:
36
+ * import { createArticleHandlers } from '@molecule/api-resource-article'
38
37
  *
39
- * router.post('/api/articles', authenticate, async (req, res) => {
40
- * const article = await createArticle(userId, req.body.article)
41
- * res.status(201).json({ article: { ...article, author: await profileOf(article.authorId) } })
38
+ * const publishing = createArticleHandlers({
39
+ * mapRequest: (req) => ({ body: req.body?.entry }),
40
+ * mapResponse: async (result) => {
41
+ * // Preserve validation, authorization, missing rows and empty deletes.
42
+ * if (result.statusCode >= 400 || result.statusCode === 204) return result
43
+ * // The app owns its projection. A list can batch-load author profiles here.
44
+ * return { ...result, body: { entry: result.body } }
45
+ * },
42
46
  * })
47
+ * router.post('/entries', publishing.create) // authenticated session remains required
48
+ * router.get('/entries/:slug', publishing.read)
43
49
  *
44
- * const page = await listArticles({ tag: 'dragons', limit: 20, offset: 0, viewerId })
45
- * // page.data[0].favorited, page.data[0].favoritesCount, page.total
50
+ * // mapRequest can also resolve an external filter name to a user id in req.query.
51
+ * // If a lookup finds nothing, return { response: { statusCode, body } } with
52
+ * // this API's empty-page response before querying. Never drop the filter.
53
+ * // Keep extra domain validation in route middleware before these handlers.
54
+ * // For a different domain model or custom workflow, call createArticle/listArticles
55
+ * // from a local route instead. The default requestHandlerMap never adopts these mappings.
46
56
  * ```
47
57
  *
48
58
  * @example
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsHG;AAEH,cAAc,wBAAwB,CAAA;AACtC,cAAc,oBAAoB,CAAA;AAClC,cAAc,qBAAqB,CAAA;AACnC,cAAc,wBAAwB,CAAA;AACtC,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA;AAC1B,cAAc,iBAAiB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgIG;AAEH,cAAc,wBAAwB,CAAA;AACtC,cAAc,oBAAoB,CAAA;AAClC,cAAc,qBAAqB,CAAA;AACnC,cAAc,wBAAwB,CAAA;AACtC,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA;AAC1B,cAAc,iBAAiB,CAAA"}
package/dist/index.js CHANGED
@@ -32,17 +32,27 @@
32
32
  *
33
33
  * @example
34
34
  * ```typescript
35
- * // An API with its own response shape (a spec you must match) uses the
36
- * // service and writes its own envelope:
37
- * import { createArticle, listArticles } from '@molecule/api-resource-article'
35
+ * // Configure a publishing API's envelopes without rewriting its operations:
36
+ * import { createArticleHandlers } from '@molecule/api-resource-article'
38
37
  *
39
- * router.post('/api/articles', authenticate, async (req, res) => {
40
- * const article = await createArticle(userId, req.body.article)
41
- * res.status(201).json({ article: { ...article, author: await profileOf(article.authorId) } })
38
+ * const publishing = createArticleHandlers({
39
+ * mapRequest: (req) => ({ body: req.body?.entry }),
40
+ * mapResponse: async (result) => {
41
+ * // Preserve validation, authorization, missing rows and empty deletes.
42
+ * if (result.statusCode >= 400 || result.statusCode === 204) return result
43
+ * // The app owns its projection. A list can batch-load author profiles here.
44
+ * return { ...result, body: { entry: result.body } }
45
+ * },
42
46
  * })
47
+ * router.post('/entries', publishing.create) // authenticated session remains required
48
+ * router.get('/entries/:slug', publishing.read)
43
49
  *
44
- * const page = await listArticles({ tag: 'dragons', limit: 20, offset: 0, viewerId })
45
- * // page.data[0].favorited, page.data[0].favoritesCount, page.total
50
+ * // mapRequest can also resolve an external filter name to a user id in req.query.
51
+ * // If a lookup finds nothing, return { response: { statusCode, body } } with
52
+ * // this API's empty-page response before querying. Never drop the filter.
53
+ * // Keep extra domain validation in route middleware before these handlers.
54
+ * // For a different domain model or custom workflow, call createArticle/listArticles
55
+ * // from a local route instead. The default requestHandlerMap never adopts these mappings.
46
56
  * ```
47
57
  *
48
58
  * @example
@@ -3,18 +3,17 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- import { create, del, feed, list, read, tags, update } from './handlers/index.js';
7
6
  /**
8
7
  * Handler map for article routes.
9
8
  */
10
9
  export declare const requestHandlerMap: {
11
- readonly create: typeof create;
12
- readonly list: typeof list;
13
- readonly feed: typeof feed;
14
- readonly tags: typeof tags;
15
- readonly read: typeof read;
16
- readonly update: typeof update;
17
- readonly del: typeof del;
10
+ readonly create: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
11
+ readonly list: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
12
+ readonly feed: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
13
+ readonly tags: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
14
+ readonly read: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
15
+ readonly update: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
16
+ readonly del: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
18
17
  readonly favorite: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
19
18
  readonly unfavorite: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
20
19
  };
@@ -1 +1 @@
1
- {"version":3,"file":"requestHandlerMap.d.ts","sourceRoot":"","sources":["../src/requestHandlerMap.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,MAAM,EACN,GAAG,EAEH,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,EAEJ,MAAM,EACP,MAAM,qBAAqB,CAAA;AAE5B;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;CAUpB,CAAA"}
1
+ {"version":3,"file":"requestHandlerMap.d.ts","sourceRoot":"","sources":["../src/requestHandlerMap.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAcH;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;CAUpB,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/api-resource-article",
3
- "version": "1.1.6",
3
+ "version": "1.2.0",
4
4
  "description": "Articles and blog posts: unique slugs, tags, favorites, a followed-authors feed, and filtered, paginated lists",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -38,7 +38,9 @@
38
38
  "@molecule/api-resource-follow": "1.0.11",
39
39
  "@molecule/api-resource-reaction": "1.0.7",
40
40
  "@molecule/api-slug": "1.0.3",
41
+ "@types/express": "5.0.6",
41
42
  "@types/node": "26.6.5",
43
+ "express": "5.3.0",
42
44
  "typescript": "6.0.3",
43
45
  "vitest": "4.1.12",
44
46
  "zod": "4.6.7"
@@ -47,17 +49,12 @@
47
49
  "@molecule/api-database": "^1.0.1",
48
50
  "@molecule/api-i18n": "^1.0.1",
49
51
  "@molecule/api-logger": "^1.0.1",
50
- "@molecule/api-resource": "^1.0.1",
52
+ "@molecule/api-resource": "^1.1.0",
51
53
  "@molecule/api-resource-follow": "^1.0.5",
52
54
  "@molecule/api-resource-reaction": "^1.0.3",
53
55
  "@molecule/api-slug": "^1.0.0",
54
56
  "zod": "^4.0.0"
55
57
  },
56
- "peerDependenciesMeta": {
57
- "@molecule/api-resource": {
58
- "optional": true
59
- }
60
- },
61
58
  "repository": {
62
59
  "type": "git",
63
60
  "url": "https://github.com/molecule-dev/molecule.git",