@molecule/api-resource-comment 1.0.5 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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-08-04T01:49:10.106Z
6
+ Generated: 2026-10-15T14:22:29.350Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-resource-comment
@@ -127,6 +127,19 @@ interface UpdateCommentInput {
127
127
  }
128
128
  ```
129
129
 
130
+ ### Types
131
+
132
+ #### `NumberedComment`
133
+
134
+ A comment together with its sequential number.
135
+
136
+ ```typescript
137
+ type NumberedComment = Comment & {
138
+ /** The comment's sequential integer number (1, 2, 3, …). */
139
+ number: number
140
+ }
141
+ ```
142
+
130
143
  ### Functions
131
144
 
132
145
  #### `commentCount(req, res)`
@@ -140,6 +153,19 @@ function commentCount(req: MoleculeRequest, res: MoleculeResponse): Promise<void
140
153
  - `req` — The request with `resourceType` and `resourceId` params.
141
154
  - `res` — The response object.
142
155
 
156
+ #### `commentNumbers(commentIds)`
157
+
158
+ The numbers of the given comments, for listing them with their numbers.
159
+ Comments without a number are left out of the map.
160
+
161
+ ```typescript
162
+ function commentNumbers(commentIds: readonly string[]): Promise<Map<string, number>>
163
+ ```
164
+
165
+ - `commentIds` — The comments' UUIDs.
166
+
167
+ **Returns:** Each numbered comment's UUID mapped to its number.
168
+
143
169
  #### `create(req, res)`
144
170
 
145
171
  Creates a new comment on a resource.
@@ -171,6 +197,26 @@ function createComment(
171
197
 
172
198
  **Returns:** The created comment.
173
199
 
200
+ #### `createNumberedComment(resourceType, resourceId, userId, data)`
201
+
202
+ Creates a comment and its number together: both are written, or neither.
203
+
204
+ ```typescript
205
+ function createNumberedComment(
206
+ resourceType: string,
207
+ resourceId: string,
208
+ userId: string,
209
+ data: CreateCommentInput,
210
+ ): Promise<NumberedComment>
211
+ ```
212
+
213
+ - `resourceType` — The type of resource being commented on.
214
+ - `resourceId` — The ID of the resource being commented on.
215
+ - `userId` — The ID of the commenting user.
216
+ - `data` — The comment creation input.
217
+
218
+ **Returns:** The created comment with its number.
219
+
174
220
  #### `del(req, res)`
175
221
 
176
222
  Deletes a comment. Only the comment owner can delete.
@@ -207,6 +253,18 @@ function getCommentById(commentId: string): Promise<Comment | null>
207
253
 
208
254
  **Returns:** The comment or `null` if not found.
209
255
 
256
+ #### `getCommentByNumber(number)`
257
+
258
+ The comment a number belongs to.
259
+
260
+ ```typescript
261
+ function getCommentByNumber(number: number): Promise<NumberedComment | null>
262
+ ```
263
+
264
+ - `number` — The comment's sequential number.
265
+
266
+ **Returns:** The comment with its number, or `null` when no comment has it.
267
+
210
268
  #### `getCommentCount(resourceType, resourceId)`
211
269
 
212
270
  Returns the total number of comments on a resource (including replies).
@@ -266,6 +324,19 @@ function list(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
266
324
  - `req` — The request with `resourceType` and `resourceId` params.
267
325
  - `res` — The response object.
268
326
 
327
+ #### `numberComment(commentId)`
328
+
329
+ The comment's number, allocating the next one when it has none. Numbers are
330
+ unique and increase.
331
+
332
+ ```typescript
333
+ function numberComment(commentId: string): Promise<number>
334
+ ```
335
+
336
+ - `commentId` — The comment's UUID.
337
+
338
+ **Returns:** Its sequential number.
339
+
269
340
  #### `read(req, res)`
270
341
 
271
342
  Retrieves a single comment by ID.
@@ -403,7 +474,7 @@ const updateCommentSchema: z.ZodObject<{ body: z.ZodString }, z.core.$strip>
403
474
 
404
475
  Peer dependencies:
405
476
 
406
- - `@molecule/api-database` ^1.0.1
477
+ - `@molecule/api-database` ^1.1.0
407
478
  - `@molecule/api-i18n` ^1.0.1
408
479
  - `@molecule/api-logger` ^1.0.1
409
480
  - `@molecule/api-resource` ^1.0.1
@@ -425,6 +496,10 @@ Peer dependencies:
425
496
  - **Migration required.** `src/__setup__/comments.sql` ships with this package
426
497
  and must exist in the target database before use (scaffolded apps apply it
427
498
  automatically; existing apps must apply it first).
499
+ - **Integer comment ids (RealWorld's `comment.id`, most public API specs):** keep the
500
+ UUID and give each comment a sequential number — `createNumberedComment()` creates both
501
+ in one transaction, `getCommentByNumber(n)` finds it, `commentNumbers(ids)` maps a list.
502
+ Apply `src/__setup__/comment_numbers.sql` too. Never build your own id-mapping table.
428
503
  - **Reads are PUBLIC by default.** `list`, `read`, `replies`, and `count` ship
429
504
  with no auth middleware (comment threads on public content). If the
430
505
  commented resources are private in your app, add an authorizer that checks
package/dist/index.d.ts CHANGED
@@ -28,6 +28,10 @@
28
28
  * - **Migration required.** `src/__setup__/comments.sql` ships with this package
29
29
  * and must exist in the target database before use (scaffolded apps apply it
30
30
  * automatically; existing apps must apply it first).
31
+ * - **Integer comment ids (RealWorld's `comment.id`, most public API specs):** keep the
32
+ * UUID and give each comment a sequential number — `createNumberedComment()` creates both
33
+ * in one transaction, `getCommentByNumber(n)` finds it, `commentNumbers(ids)` maps a list.
34
+ * Apply `src/__setup__/comment_numbers.sql` too. Never build your own id-mapping table.
31
35
  * - **Reads are PUBLIC by default.** `list`, `read`, `replies`, and `count` ship
32
36
  * with no auth middleware (comment threads on public content). If the
33
37
  * commented resources are private in your app, add an authorizer that checks
@@ -60,6 +64,7 @@
60
64
  export * from './authorizers/index.js';
61
65
  export * from './browser-guard.js';
62
66
  export * from './handlers/index.js';
67
+ export * from './numbers.js';
63
68
  export * from './requestHandlerMap.js';
64
69
  export * from './routes.js';
65
70
  export * from './service.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8DG;AAEH,cAAc,wBAAwB,CAAA;AACtC,cAAc,oBAAoB,CAAA;AAClC,cAAc,qBAAqB,CAAA;AACnC,cAAc,cAAc,CAAA;AAC5B,cAAc,wBAAwB,CAAA;AACtC,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA;AAC1B,cAAc,iBAAiB,CAAA"}
package/dist/index.js CHANGED
@@ -28,6 +28,10 @@
28
28
  * - **Migration required.** `src/__setup__/comments.sql` ships with this package
29
29
  * and must exist in the target database before use (scaffolded apps apply it
30
30
  * automatically; existing apps must apply it first).
31
+ * - **Integer comment ids (RealWorld's `comment.id`, most public API specs):** keep the
32
+ * UUID and give each comment a sequential number — `createNumberedComment()` creates both
33
+ * in one transaction, `getCommentByNumber(n)` finds it, `commentNumbers(ids)` maps a list.
34
+ * Apply `src/__setup__/comment_numbers.sql` too. Never build your own id-mapping table.
31
35
  * - **Reads are PUBLIC by default.** `list`, `read`, `replies`, and `count` ship
32
36
  * with no auth middleware (comment threads on public content). If the
33
37
  * commented resources are private in your app, add an authorizer that checks
@@ -60,6 +64,7 @@
60
64
  export * from './authorizers/index.js';
61
65
  export * from './browser-guard.js';
62
66
  export * from './handlers/index.js';
67
+ export * from './numbers.js';
63
68
  export * from './requestHandlerMap.js';
64
69
  export * from './routes.js';
65
70
  export * from './service.js';
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Sequential integer numbers for comments, for APIs whose clients address a
3
+ * comment by an integer (RealWorld's `comment.id` is one; so are most public
4
+ * API specs). The comment keeps its UUID; the number lives in
5
+ * `comment_numbers` and is allocated once, at most one per comment.
6
+ *
7
+ * @module
8
+ */
9
+ import type { Comment, CreateCommentInput } from './types.js';
10
+ /** A comment together with its sequential number. */
11
+ export type NumberedComment = Comment & {
12
+ /** The comment's sequential integer number (1, 2, 3, …). */
13
+ number: number;
14
+ };
15
+ /**
16
+ * The comment's number, allocating the next one when it has none. Numbers are
17
+ * unique and increase.
18
+ *
19
+ * @param commentId - The comment's UUID.
20
+ * @returns Its sequential number.
21
+ * @throws {Error} When no number could be allocated after several attempts.
22
+ */
23
+ export declare function numberComment(commentId: string): Promise<number>;
24
+ /**
25
+ * Creates a comment and its number together: both are written, or neither.
26
+ *
27
+ * @param resourceType - The type of resource being commented on.
28
+ * @param resourceId - The ID of the resource being commented on.
29
+ * @param userId - The ID of the commenting user.
30
+ * @param data - The comment creation input.
31
+ * @returns The created comment with its number.
32
+ */
33
+ export declare function createNumberedComment(resourceType: string, resourceId: string, userId: string, data: CreateCommentInput): Promise<NumberedComment>;
34
+ /**
35
+ * The comment a number belongs to.
36
+ *
37
+ * @param number - The comment's sequential number.
38
+ * @returns The comment with its number, or `null` when no comment has it.
39
+ */
40
+ export declare function getCommentByNumber(number: number): Promise<NumberedComment | null>;
41
+ /**
42
+ * The numbers of the given comments, for listing them with their numbers.
43
+ * Comments without a number are left out of the map.
44
+ *
45
+ * @param commentIds - The comments' UUIDs.
46
+ * @returns Each numbered comment's UUID mapped to its number.
47
+ */
48
+ export declare function commentNumbers(commentIds: readonly string[]): Promise<Map<string, number>>;
49
+ //# sourceMappingURL=numbers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"numbers.d.ts","sourceRoot":"","sources":["../src/numbers.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAWH,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAI7D,qDAAqD;AACrD,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG;IACtC,4DAA4D;IAC5D,MAAM,EAAE,MAAM,CAAA;CACf,CAAA;AAuDD;;;;;;;GAOG;AACH,wBAAsB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEtE;AAED;;;;;;;;GAQG;AACH,wBAAsB,qBAAqB,CACzC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,kBAAkB,GACvB,OAAO,CAAC,eAAe,CAAC,CAK1B;AAED;;;;;GAKG;AACH,wBAAsB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAQxF;AAED;;;;;;GAMG;AACH,wBAAsB,cAAc,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAMhG"}
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Sequential integer numbers for comments, for APIs whose clients address a
3
+ * comment by an integer (RealWorld's `comment.id` is one; so are most public
4
+ * API specs). The comment keeps its UUID; the number lives in
5
+ * `comment_numbers` and is allocated once, at most one per comment.
6
+ *
7
+ * @module
8
+ */
9
+ import { create as dbCreate, findMany, findOne, getActiveTransaction, withTransaction, } from '@molecule/api-database';
10
+ import { createComment, getCommentById } from './service.js';
11
+ const NUMBERS = 'comment_numbers';
12
+ /** How many times the work is redone when a concurrent writer took the number first. */
13
+ const MAX_ATTEMPTS = 5;
14
+ /**
15
+ * Runs `work` in its own transaction, again when it fails: a concurrent
16
+ * writer that took the same number fails the unique key, and the next
17
+ * attempt allocates the next number. Inside a caller's transaction a failed
18
+ * statement can poison it (Postgres), so there the work runs once and the
19
+ * caller decides.
20
+ *
21
+ * @param what - What is being numbered, for the error.
22
+ * @param work - The allocation.
23
+ * @returns What `work` resolves to.
24
+ */
25
+ async function withNumberRetry(what, work) {
26
+ if (getActiveTransaction())
27
+ return work();
28
+ for (let attempt = 1;; attempt++) {
29
+ try {
30
+ return await withTransaction(work);
31
+ }
32
+ catch (error) {
33
+ if (attempt >= MAX_ATTEMPTS)
34
+ throw new Error(`Could not number ${what}`, { cause: error });
35
+ // Rolled back; a concurrent writer most likely took the number (its
36
+ // unique key failed). The next attempt reads the new highest number.
37
+ }
38
+ }
39
+ }
40
+ /**
41
+ * Allocates the next number for a comment that has none (no transaction of its own).
42
+ *
43
+ * @param commentId - The comment's UUID.
44
+ * @returns Its number.
45
+ */
46
+ async function allocate(commentId) {
47
+ const existing = await findOne(NUMBERS, [
48
+ { field: 'commentId', operator: '=', value: commentId },
49
+ ]);
50
+ if (existing)
51
+ return Number(existing.number);
52
+ const [last] = await findMany(NUMBERS, {
53
+ orderBy: [{ field: 'number', direction: 'desc' }],
54
+ limit: 1,
55
+ });
56
+ const number = (last ? Number(last.number) : 0) + 1;
57
+ await dbCreate(NUMBERS, { number, commentId });
58
+ return number;
59
+ }
60
+ /**
61
+ * The comment's number, allocating the next one when it has none. Numbers are
62
+ * unique and increase.
63
+ *
64
+ * @param commentId - The comment's UUID.
65
+ * @returns Its sequential number.
66
+ * @throws {Error} When no number could be allocated after several attempts.
67
+ */
68
+ export async function numberComment(commentId) {
69
+ return withNumberRetry(`comment ${commentId}`, () => allocate(commentId));
70
+ }
71
+ /**
72
+ * Creates a comment and its number together: both are written, or neither.
73
+ *
74
+ * @param resourceType - The type of resource being commented on.
75
+ * @param resourceId - The ID of the resource being commented on.
76
+ * @param userId - The ID of the commenting user.
77
+ * @param data - The comment creation input.
78
+ * @returns The created comment with its number.
79
+ */
80
+ export async function createNumberedComment(resourceType, resourceId, userId, data) {
81
+ return withNumberRetry('a new comment', async () => {
82
+ const comment = await createComment(resourceType, resourceId, userId, data);
83
+ return { ...comment, number: await allocate(comment.id) };
84
+ });
85
+ }
86
+ /**
87
+ * The comment a number belongs to.
88
+ *
89
+ * @param number - The comment's sequential number.
90
+ * @returns The comment with its number, or `null` when no comment has it.
91
+ */
92
+ export async function getCommentByNumber(number) {
93
+ if (!Number.isInteger(number) || number < 1)
94
+ return null;
95
+ const row = await findOne(NUMBERS, [
96
+ { field: 'number', operator: '=', value: number },
97
+ ]);
98
+ if (!row)
99
+ return null;
100
+ const comment = await getCommentById(row.commentId);
101
+ return comment ? { ...comment, number: Number(row.number) } : null;
102
+ }
103
+ /**
104
+ * The numbers of the given comments, for listing them with their numbers.
105
+ * Comments without a number are left out of the map.
106
+ *
107
+ * @param commentIds - The comments' UUIDs.
108
+ * @returns Each numbered comment's UUID mapped to its number.
109
+ */
110
+ export async function commentNumbers(commentIds) {
111
+ if (commentIds.length === 0)
112
+ return new Map();
113
+ const rows = await findMany(NUMBERS, {
114
+ where: [{ field: 'commentId', operator: 'in', value: [...commentIds] }],
115
+ });
116
+ return new Map(rows.map((r) => [r.commentId, Number(r.number)]));
117
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/api-resource-comment",
3
- "version": "1.0.5",
3
+ "version": "1.1.0",
4
4
  "description": "Threaded comments on any resource with polymorphic attachment and pagination",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -29,13 +29,15 @@
29
29
  ],
30
30
  "license": "Apache-2.0",
31
31
  "devDependencies": {
32
+ "@molecule/api-database": "1.1.0",
33
+ "@molecule/api-database-sqlite": "1.1.0",
32
34
  "@types/node": "26.1.2",
33
35
  "typescript": "6.0.3",
34
36
  "vitest": "4.1.11",
35
37
  "zod": "4.4.3"
36
38
  },
37
39
  "peerDependencies": {
38
- "@molecule/api-database": "^1.0.1",
40
+ "@molecule/api-database": "^1.1.0",
39
41
  "@molecule/api-i18n": "^1.0.1",
40
42
  "@molecule/api-logger": "^1.0.1",
41
43
  "@molecule/api-resource": "^1.0.1",
@@ -0,0 +1,8 @@
1
+ -- Sequential integer numbers for comments, for APIs whose clients address a
2
+ -- comment by an integer id (RealWorld's `comment.id` is an integer). Opt-in:
3
+ -- written by numberComment() / createNumberedComment(); comments without a
4
+ -- number keep working by their UUID.
5
+ CREATE TABLE IF NOT EXISTS "comment_numbers" (
6
+ "number" INTEGER PRIMARY KEY,
7
+ "commentId" UUID NOT NULL UNIQUE REFERENCES "comments"("id") ON DELETE CASCADE
8
+ );