@molecule/api-resource-comment 1.0.4 → 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/LICENSE CHANGED
@@ -1,3 +1,4 @@
1
+
1
2
  Apache License
2
3
  Version 2.0, January 2004
3
4
  http://www.apache.org/licenses/
@@ -34,21 +35,33 @@
34
35
 
35
36
  "Work" shall mean the work of authorship, whether in Source or
36
37
  Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work.
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
38
40
 
39
41
  "Derivative Works" shall mean any work, whether in Source or Object
40
42
  form, that is based on (or derived from) the Work and for which the
41
43
  editorial revisions, annotations, elaborations, or other modifications
42
- represent, as a whole, an original work of authorship.
43
-
44
- "Contribution" shall mean any work of authorship, including the
45
- original version of the Work and any modifications or additions
46
- to that Work, that is intentionally submitted to the Licensor for
47
- inclusion in the Work by the copyright owner or by an individual or
48
- Legal Entity authorized to submit on behalf of the copyright owner.
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
49
62
 
50
63
  "Contributor" shall mean Licensor and any individual or Legal Entity
51
- on behalf of whom a Contribution has been received by the Licensor and
64
+ on behalf of whom a Contribution has been received by Licensor and
52
65
  subsequently incorporated within the Work.
53
66
 
54
67
  2. Grant of Copyright License. Subject to the terms and conditions of
@@ -61,8 +74,18 @@
61
74
  3. Grant of Patent License. Subject to the terms and conditions of
62
75
  this License, each Contributor hereby grants to You a perpetual,
63
76
  worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
- patent license to make, have made, use, offer to sell, sell, import,
65
- and otherwise transfer the Work.
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
66
89
 
67
90
  4. Redistribution. You may reproduce and distribute copies of the
68
91
  Work or Derivative Works thereof in any medium, with or without
@@ -84,23 +107,87 @@
84
107
  (d) If the Work includes a "NOTICE" text file as part of its
85
108
  distribution, then any Derivative Works that You distribute must
86
109
  include a readable copy of the attribution notices contained
87
- within such NOTICE file.
88
-
89
- 5. Submission of Contributions.
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
90
138
 
91
139
  6. Trademarks. This License does not grant permission to use the trade
92
- names, trademarks, service marks, or product names of the Licensor.
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
93
143
 
94
144
  7. Disclaimer of Warranty. Unless required by applicable law or
95
- agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
-
98
- 8. Limitation of Liability. In no event and under no legal theory shall
99
- any Contributor be liable to You for damages.
100
-
101
- 9. Accepting Warranty or Additional Liability.
102
-
103
- Copyright 2026 Molecule Dev, Inc.
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
104
191
 
105
192
  Licensed under the Apache License, Version 2.0 (the "License");
106
193
  you may not use this file except in compliance with the License.
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.4",
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",
@@ -18,6 +18,7 @@
18
18
  },
19
19
  "files": [
20
20
  "dist",
21
+ "src/__setup__",
21
22
  "README.md"
22
23
  ],
23
24
  "keywords": [
@@ -28,13 +29,15 @@
28
29
  ],
29
30
  "license": "Apache-2.0",
30
31
  "devDependencies": {
32
+ "@molecule/api-database": "1.1.0",
33
+ "@molecule/api-database-sqlite": "1.1.0",
31
34
  "@types/node": "26.1.2",
32
35
  "typescript": "6.0.3",
33
36
  "vitest": "4.1.11",
34
37
  "zod": "4.4.3"
35
38
  },
36
39
  "peerDependencies": {
37
- "@molecule/api-database": "^1.0.1",
40
+ "@molecule/api-database": "^1.1.0",
38
41
  "@molecule/api-i18n": "^1.0.1",
39
42
  "@molecule/api-logger": "^1.0.1",
40
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
+ );
@@ -0,0 +1,15 @@
1
+ CREATE TABLE IF NOT EXISTS "comments" (
2
+ "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
3
+ "resourceType" VARCHAR(255) NOT NULL,
4
+ "resourceId" VARCHAR(255) NOT NULL,
5
+ "userId" UUID NOT NULL,
6
+ "parentId" UUID REFERENCES "comments"("id") ON DELETE CASCADE,
7
+ "body" TEXT NOT NULL,
8
+ "editedAt" TIMESTAMPTZ,
9
+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT now(),
10
+ "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT now()
11
+ );
12
+
13
+ CREATE INDEX IF NOT EXISTS "idx_comments_resource" ON "comments" ("resourceType", "resourceId");
14
+ CREATE INDEX IF NOT EXISTS "idx_comments_parent" ON "comments" ("parentId");
15
+ CREATE INDEX IF NOT EXISTS "idx_comments_user" ON "comments" ("userId");