@molecule/api-resource-article 1.1.6 → 1.2.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/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-07T08:32:12.976Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-resource-article
@@ -22,6 +22,32 @@ favorites and follows the rest of the app sees.
22
22
  unique, and `article_tags.position` is the order the tags were given in). It also ships
23
23
  `src/__setup__/reactions.sql` and `src/__setup__/follows.sql`, which create the `reactions` and `follows` tables it reads by name.
24
24
 
25
+ **HTTP format is configuration.** In the scaffold's `App/Resource/Article/index.ts`,
26
+ export `requestHandlerMap = createArticleHandlers({ mapRequest, mapResponse })`.
27
+ Keep `create`, `list`, `feed`, `read`, `update`, `del`, `favorite`, `unfavorite`
28
+ and `tags` in the package.
29
+ `mapRequest` can unwrap bodies and resolve query filters. Async `mapResponse`
30
+ can batch-load author profiles, omit fields from list items, rename pagination
31
+ keys, wrap results, or translate error statuses and bodies. It receives errors
32
+ and empty deletes too. Set the authenticated user on `res.locals.session.userId`.
33
+
34
+ ```typescript
35
+ import { createArticleHandlers } from '@molecule/api-resource-article'
36
+
37
+ export const requestHandlerMap = createArticleHandlers({
38
+ mapRequest: (req) => ({ body: req.body?.entry }),
39
+ mapResponse: (result) =>
40
+ result.statusCode >= 400 || result.statusCode === 204
41
+ ? result
42
+ : { ...result, body: { entry: result.body } },
43
+ })
44
+ ```
45
+
46
+ Use the resulting map's handlers on the app's routes. For distinct route projections,
47
+ create separate maps with separate options. The static `requestHandlerMap` keeps the
48
+ native flat-body/raw-article format. Use service functions for a different domain workflow.
49
+ Read Quick Start for filter mapping and early responses.
50
+
25
51
  > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
26
52
  > It is written to be read by coding agents as much as by people, and is generated from this
27
53
  > package's source — edit `src/index.ts` JSDoc, not this file.
@@ -44,17 +70,27 @@ import { routes, requestHandlerMap } from '@molecule/api-resource-article'
44
70
  ```
45
71
 
46
72
  ```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'
73
+ // Configure a publishing API's envelopes without rewriting its operations:
74
+ import { createArticleHandlers } from '@molecule/api-resource-article'
50
75
 
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) } })
76
+ const publishing = createArticleHandlers({
77
+ mapRequest: (req) => ({ body: req.body?.entry }),
78
+ mapResponse: async (result) => {
79
+ // Preserve validation, authorization, missing rows and empty deletes.
80
+ if (result.statusCode >= 400 || result.statusCode === 204) return result
81
+ // The app owns its projection. A list can batch-load author profiles here.
82
+ return { ...result, body: { entry: result.body } }
83
+ },
54
84
  })
85
+ router.post('/entries', publishing.create) // authenticated session remains required
86
+ router.get('/entries/:slug', publishing.read)
55
87
 
56
- const page = await listArticles({ tag: 'dragons', limit: 20, offset: 0, viewerId })
57
- // page.data[0].favorited, page.data[0].favoritesCount, page.total
88
+ // mapRequest can also resolve an external filter name to a user id in req.query.
89
+ // If a lookup finds nothing, return { response: { statusCode, body } } with
90
+ // this API's empty-page response before querying. Never drop the filter.
91
+ // Keep extra domain validation in route middleware before these handlers.
92
+ // For a different domain model or custom workflow, call createArticle/listArticles
93
+ // from a local route instead. The default requestHandlerMap never adopts these mappings.
58
94
  ```
59
95
 
60
96
  ```typescript
@@ -227,97 +263,42 @@ interface TagCount {
227
263
 
228
264
  ### Types
229
265
 
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
- ```
266
+ #### `ArticleRequestHandlerMap`
238
267
 
239
- ### Functions
240
-
241
- #### `create(req, res)`
242
-
243
- `POST /articles` — create an article as the signed-in user.
268
+ HTTP handlers for all article routes. Authorization stays in each operation.
244
269
 
245
270
  ```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)`
253
-
254
- `GET /articles` — newest first; `?tag=`, `?author=` (user id),
255
- `?favoritedBy=` (user id), `?limit=`, `?offset=`.
256
-
257
- ```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>
271
+ type ArticleRequestHandlerMap = {
272
+ [Name in keyof typeof operations]: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
273
+ }
284
274
  ```
285
275
 
286
- - `req` — The request; `?limit=` caps the list.
287
- - `res` — `[{ tag, count }]`.
288
-
289
- #### `read(req, res)`
276
+ #### `AuthorChange`
290
277
 
291
- `GET /articles/:slug`.
278
+ The outcome of a change that only the author may make.
292
279
 
293
280
  ```typescript
294
- function read(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
281
+ type AuthorChange<T> =
282
+ { status: 'ok'; article: T } | { status: 'not_found' } | { status: 'forbidden' }
295
283
  ```
296
284
 
297
- - `req` — The request.
298
- - `res` — The article, or 404.
285
+ ### Functions
299
286
 
300
- #### `update(req, res)`
287
+ #### `createArticleHandlers(options)`
301
288
 
302
- `PUT /articles/:slug` — author only; a new title gives a new slug.
289
+ Create article handlers for this project's wire format. Adapt an envelope,
290
+ filter names or response projection without rewriting the article operations.
291
+ Each mapping receives the adapted request and its original response context.
292
+ Omit the options for the standard flat-body, raw-article and paginated-list API.
293
+ Error and partial responses reach mapResponse too, so preserve them explicitly.
303
294
 
304
295
  ```typescript
305
- function update(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
296
+ function createArticleHandlers(options?: RequestHandlerOptions): ArticleRequestHandlerMap
306
297
  ```
307
298
 
308
- - `req` — Body: any of `{ title, description, body, tagList }`.
309
- - `res` — The updated article, 403 or 404.
310
-
311
- #### `del(req, res)`
299
+ - `options` — Shared resource request/response mappings, scoped to this map.
312
300
 
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.
301
+ **Returns:** A route-compatible map with the same names as requestHandlerMap.
321
302
 
322
303
  #### `hydrateArticles(rows, viewerId)`
323
304
 
@@ -497,9 +478,65 @@ function popularTags(limit?: number): Promise<TagCount[]>
497
478
 
498
479
  ### Constants
499
480
 
481
+ #### `create`
482
+
483
+ Create an article from a flat body as the session user.
484
+
485
+ ```typescript
486
+ const create: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
487
+ ```
488
+
489
+ #### `list`
490
+
491
+ List articles with the standard filters and pagination envelope.
492
+
493
+ ```typescript
494
+ const list: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
495
+ ```
496
+
497
+ #### `feed`
498
+
499
+ List articles by followed authors for the session user.
500
+
501
+ ```typescript
502
+ const feed: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
503
+ ```
504
+
505
+ #### `tags`
506
+
507
+ Return tags in use, optionally capped by the requested limit.
508
+
509
+ ```typescript
510
+ const tags: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
511
+ ```
512
+
513
+ #### `read`
514
+
515
+ Read an article by slug, including the viewer's favorite state.
516
+
517
+ ```typescript
518
+ const read: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
519
+ ```
520
+
521
+ #### `update`
522
+
523
+ Update an article as its author.
524
+
525
+ ```typescript
526
+ const update: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
527
+ ```
528
+
529
+ #### `del`
530
+
531
+ Delete an article as its author, returning an empty 204.
532
+
533
+ ```typescript
534
+ const del: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
535
+ ```
536
+
500
537
  #### `favorite`
501
538
 
502
- `POST /articles/:slug/favorite` — idempotent; returns the article.
539
+ Favorite an article as the session user.
503
540
 
504
541
  ```typescript
505
542
  const favorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
@@ -507,7 +544,7 @@ const favorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
507
544
 
508
545
  #### `unfavorite`
509
546
 
510
- `DELETE /articles/:slug/favorite` — idempotent; returns the article.
547
+ Unfavorite an article as the session user.
511
548
 
512
549
  ```typescript
513
550
  const unfavorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
@@ -519,13 +556,13 @@ Handler map for article routes.
519
556
 
520
557
  ```typescript
521
558
  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
559
+ readonly create: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
560
+ readonly list: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
561
+ readonly feed: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
562
+ readonly tags: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
563
+ readonly read: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
564
+ readonly update: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
565
+ readonly del: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
529
566
  readonly favorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
530
567
  readonly unfavorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
531
568
  }
@@ -653,7 +690,7 @@ Peer dependencies:
653
690
  - `@molecule/api-database` ^1.0.1
654
691
  - `@molecule/api-i18n` ^1.0.1
655
692
  - `@molecule/api-logger` ^1.0.1
656
- - `@molecule/api-resource` ^1.0.1
693
+ - `@molecule/api-resource` ^1.1.0
657
694
  - `@molecule/api-resource-follow` ^1.0.5
658
695
  - `@molecule/api-resource-reaction` ^1.0.3
659
696
  - `@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';