@molecule/api-resource-comment 1.5.0 → 1.6.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-11-30T19:05:14.944Z
6
+ Generated: 2026-11-30T22:00:39.878Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-resource-comment
@@ -45,7 +45,7 @@ import { routes, requestHandlerMap } from '@molecule/api-resource-comment'
45
45
  ## Installation
46
46
 
47
47
  ```bash
48
- npm install @molecule/api-resource-comment @molecule/api-database @molecule/api-i18n @molecule/api-logger @molecule/api-rate-limit express zod
48
+ npm install @molecule/api-resource-comment @molecule/api-database @molecule/api-i18n @molecule/api-logger @molecule/api-rate-limit @molecule/api-resource express zod
49
49
  npm install -D @types/express
50
50
  ```
51
51
 
@@ -103,8 +103,10 @@ interface Comment {
103
103
  resourceType: string
104
104
  /** The ID of the resource this comment is attached to. */
105
105
  resourceId: string
106
- /** The ID of the user who created this comment. */
107
- userId: string
106
+ /** The ID of the user who created this comment, or `null` for guest comments. */
107
+ userId: string | null
108
+ /** Display name supplied for a guest comment, or `null` for authenticated comments. */
109
+ authorName?: string | null
108
110
  /** Hydrated public author profile when `@molecule/api-resource-user` is loaded. */
109
111
  author?: CommentAuthor | null
110
112
  /** The parent comment ID for threaded replies, or `null` for top-level comments. */
@@ -130,6 +132,8 @@ interface CreateCommentInput {
130
132
  body: string
131
133
  /** Optional parent comment ID for threaded replies. */
132
134
  parentId?: string
135
+ /** Display name when posting as an unauthenticated guest (ignored when signed in). */
136
+ authorName?: string
133
137
  }
134
138
  ```
135
139
 
@@ -421,7 +425,7 @@ result by `number` and read it back with `getCommentByNumber(number)`.
421
425
  function createNumberedComment(
422
426
  resourceType: string,
423
427
  resourceId: string,
424
- userId: string,
428
+ userId: string | null,
425
429
  data: CreateCommentInput,
426
430
  ): Promise<NumberedComment>
427
431
  ```
@@ -483,7 +487,7 @@ Both `__setup__` SQL files are required (`comments`, `comment_numbers`).
483
487
  function createComment(
484
488
  resourceType: string,
485
489
  resourceId: string,
486
- userId: string,
490
+ userId: string | null,
487
491
  data: CreateCommentInput,
488
492
  ): Promise<NumberedComment>
489
493
  ```
@@ -659,7 +663,11 @@ Schema for validating comment creation input.
659
663
 
660
664
  ```typescript
661
665
  const createCommentSchema: z.ZodObject<
662
- { body: z.ZodString; parentId: z.ZodOptional<z.ZodString> },
666
+ {
667
+ body: z.ZodString
668
+ parentId: z.ZodOptional<z.ZodString>
669
+ authorName: z.ZodOptional<z.ZodString>
670
+ },
663
671
  z.core.$strip
664
672
  >
665
673
  ```
@@ -682,7 +690,7 @@ Peer dependencies:
682
690
  - `@molecule/api-i18n` ^1.0.1
683
691
  - `@molecule/api-logger` ^1.0.1
684
692
  - `@molecule/api-rate-limit` ^1.0.1
685
- - `@molecule/api-resource` ^1.0.1 _(optional)_
693
+ - `@molecule/api-resource` ^1.4.0
686
694
  - `express` ^5.0.0
687
695
  - `zod` ^4.0.0
688
696
 
@@ -692,7 +700,7 @@ Peer dependencies:
692
700
  - `@molecule/api-i18n`
693
701
  - `@molecule/api-logger`
694
702
  - `@molecule/api-rate-limit`
695
- - `@molecule/api-resource` _(optional)_
703
+ - `@molecule/api-resource`
696
704
  - `express`
697
705
  - `zod`
698
706
 
package/dist/numbers.d.ts CHANGED
@@ -42,7 +42,7 @@ export declare function numberComment(commentId: string): Promise<number>;
42
42
  * @param data - The comment creation input.
43
43
  * @returns The created comment with its number.
44
44
  */
45
- export declare function createNumberedComment(resourceType: string, resourceId: string, userId: string, data: CreateCommentInput): Promise<NumberedComment>;
45
+ export declare function createNumberedComment(resourceType: string, resourceId: string, userId: string | null, data: CreateCommentInput): Promise<NumberedComment>;
46
46
  /**
47
47
  * The comment a number belongs to — the lookup behind an integer-addressed
48
48
  * route such as `DELETE /comments/:id`: find the comment here, then pass its
@@ -1 +1 @@
1
- {"version":3,"file":"numbers.d.ts","sourceRoot":"","sources":["../src/numbers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAMH,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAK7D,qDAAqD;AACrD,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG;IACtC,4DAA4D;IAC5D,MAAM,EAAE,MAAM,CAAA;CACf,CAAA;AAQD;;;;;;;;;GASG;AACH,wBAAsB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEtE;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,qBAAqB,CACzC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,kBAAkB,GACvB,OAAO,CAAC,eAAe,CAAC,CAE1B;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAQxF;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAEhG"}
1
+ {"version":3,"file":"numbers.d.ts","sourceRoot":"","sources":["../src/numbers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAMH,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAK7D,qDAAqD;AACrD,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG;IACtC,4DAA4D;IAC5D,MAAM,EAAE,MAAM,CAAA;CACf,CAAA;AAQD;;;;;;;;;GASG;AACH,wBAAsB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEtE;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,qBAAqB,CACzC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,IAAI,EAAE,kBAAkB,GACvB,OAAO,CAAC,eAAe,CAAC,CAE1B;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAQxF;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAEhG"}
@@ -1 +1 @@
1
- {"version":3,"file":"scaffold-router.d.ts","sourceRoot":"","sources":["../src/scaffold-router.ts"],"names":[],"mappings":"AA2BA,QAAA,MAAM,MAAM,4CAAW,CAAA;AA2TvB,eAAe,MAAM,CAAA"}
1
+ {"version":3,"file":"scaffold-router.d.ts","sourceRoot":"","sources":["../src/scaffold-router.ts"],"names":[],"mappings":"AAyCA,QAAA,MAAM,MAAM,4CAAW,CAAA;AA+NvB,eAAe,MAAM,CAAA"}
@@ -1,72 +1,28 @@
1
1
  import { Router } from 'express';
2
- import { t } from '@molecule/api-i18n';
3
- import { logger } from '@molecule/api-logger';
4
2
  import { consume as consumeRateLimit, hasProvider as hasRateLimitProvider, } from '@molecule/api-rate-limit';
3
+ import { getUserId, queryLimit, queryOffset, queryString, sendError, sendNotFound, sendServerError, sendUnauthorized, sendValidationError, } from '@molecule/api-resource';
5
4
  import { canAccessCommentResource, CommentResourceAccessError, createComment, createCommentSchema, deleteComment, getCommentById, getCommentCount, getCommentsByResource, getReplies, updateComment, updateCommentSchema, } from '@molecule/api-resource-comment';
6
5
  // Edit paths, allowlisted resource types, and JSON here. Comment services own
7
6
  // persistence, sequential numbering, author hydration, and ownership checks.
8
7
  // Fail-closed access: once any sibling resource registers a policy via
9
8
  // registerResourceAccessPolicy() (e.g. articles.ts), unregistered resourceTypes
10
9
  // and private/draft parents are refused with 404.
11
- const router = Router();
12
- /** Maximum page size accepted by comment listing endpoints. */
13
- const MAX_LIST_LIMIT = 100;
14
- /** Valid slug pattern for polymorphic `resourceType` path segments. */
10
+ // Set ALLOW_GUEST_COMMENTS = true on public sites (e.g. blogs) so unauthenticated
11
+ // readers may post comments by supplying `authorName` (rate-limited; signed-in
12
+ // users always post under their account to prevent spoofing).
13
+ const ALLOW_GUEST_COMMENTS = false;
15
14
  const RESOURCE_TYPE_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/i;
16
- /** Read the authenticated session user ID without type casts. */
17
- function viewerId(res) {
18
- const session = res.locals.session;
19
- if (typeof session !== 'object' || session === null || !('userId' in session))
20
- return undefined;
21
- return typeof session.userId === 'string' && session.userId ? session.userId : undefined;
22
- }
23
- /** Read a single string route param. */
24
- function paramString(value) {
25
- return typeof value === 'string' && value.trim() ? value : undefined;
26
- }
27
- /** Read an optional bounded page size (`1..MAX_LIST_LIMIT`). */
28
- function queryLimit(value) {
29
- const parsed = parseInt(String(value ?? ''), 10);
30
- return Number.isFinite(parsed) ? Math.min(MAX_LIST_LIMIT, Math.max(1, parsed)) : 20;
31
- }
32
- /** Read an optional non-negative pagination offset. */
33
- function queryOffset(value) {
34
- const parsed = parseInt(String(value ?? ''), 10);
35
- return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;
36
- }
15
+ const router = Router();
37
16
  /** Read an optional sort direction (`'asc'` or `'desc'`). */
38
17
  function queryOrder(value) {
39
- if (value === 'asc' || value === 'desc')
40
- return value;
41
- return undefined;
42
- }
43
- /** Send an i18n-formatted error response. */
44
- function errorResponse(res, status, key, fallback) {
45
- res.status(status).json({ error: t(key, undefined, { defaultValue: fallback }), errorKey: key });
46
- }
47
- /** Answer a request missing a valid signed-in session. */
48
- function unauthorized(res) {
49
- errorResponse(res, 401, 'resource.error.unauthorized', 'Unauthorized.');
50
- }
51
- /** Answer a request for a missing or inaccessible comment or parent resource. */
52
- function notFound(res) {
53
- errorResponse(res, 404, 'resource.error.notFound', 'Not found.');
54
- }
55
- /** Answer a request with invalid input fields. */
56
- function invalid(res, issues) {
57
- res.status(400).json({
58
- error: issues
59
- .map((issue) => `${issue.path.map(String).join('.')}: ${issue.message}`)
60
- .join(', '),
61
- errorKey: 'comment.error.validationFailed',
62
- });
18
+ return value === 'asc' || value === 'desc' ? value : undefined;
63
19
  }
64
20
  /** Validate `resourceType` and `resourceId` path params. */
65
21
  function resourceParams(req, res) {
66
- const resourceType = paramString(req.params.resourceType);
67
- const resourceId = paramString(req.params.resourceId);
22
+ const resourceType = queryString(req.params.resourceType);
23
+ const resourceId = queryString(req.params.resourceId);
68
24
  if (!resourceType || !resourceId || !RESOURCE_TYPE_PATTERN.test(resourceType)) {
69
- errorResponse(res, 400, 'comment.error.missingResource', 'Resource type and ID are required');
25
+ sendError(res, 400, 'comment.error.missingResource', 'Resource type and ID are required');
70
26
  return null;
71
27
  }
72
28
  return { resourceType, resourceId };
@@ -77,60 +33,61 @@ async function rateLimitComments(req, res, next) {
77
33
  next();
78
34
  return;
79
35
  }
80
- const key = `comments:create:${viewerId(res) ?? req.ip ?? 'unknown'}`;
36
+ const key = `comments:create:${getUserId(res) ?? req.ip ?? 'unknown'}`;
81
37
  const result = await consumeRateLimit(key);
82
38
  if (!result.allowed) {
83
39
  const retryAfter = result.retryAfter ?? Math.max(1, Math.ceil((result.resetAt.getTime() - Date.now()) / 1000));
84
40
  res.set('Retry-After', String(retryAfter));
85
- errorResponse(res, 429, 'rateLimit.error.tooManyRequests', 'Too many requests. Please try again later.');
41
+ sendError(res, 429, 'rateLimit.error.tooManyRequests', 'Too many requests. Please try again later.');
86
42
  return;
87
43
  }
88
44
  next();
89
45
  }
90
46
  router.post('/:resourceType/:resourceId/comments', rateLimitComments, async (req, res) => {
91
- const userId = viewerId(res);
92
- if (!userId) {
93
- unauthorized(res);
94
- return;
95
- }
47
+ const userId = getUserId(res);
48
+ if (!userId && !ALLOW_GUEST_COMMENTS)
49
+ return sendUnauthorized(res);
96
50
  const params = resourceParams(req, res);
97
51
  if (!params)
98
52
  return;
99
53
  const parsed = createCommentSchema.safeParse(req.body);
100
54
  if (!parsed.success) {
101
- invalid(res, parsed.error.issues);
102
- return;
55
+ return sendValidationError(res, 'comment.error.validationFailed', parsed.error.issues);
56
+ }
57
+ if (!userId && !parsed.data.authorName) {
58
+ return sendValidationError(res, 'comment.error.validationFailed', [
59
+ { path: ['authorName'], message: 'Name is required' },
60
+ ]);
103
61
  }
104
62
  try {
105
63
  const comment = await createComment(params.resourceType, params.resourceId, userId, parsed.data);
106
64
  res.status(201).json(comment);
107
65
  }
108
66
  catch (error) {
109
- if (error instanceof CommentResourceAccessError) {
110
- notFound(res);
111
- return;
112
- }
113
- logger.error('Failed to create comment', { ...params, userId, error });
114
- errorResponse(res, 500, 'comment.error.createFailed', 'Failed to create comment');
67
+ if (error instanceof CommentResourceAccessError)
68
+ return sendNotFound(res);
69
+ sendServerError(res, 'comment.error.createFailed', 'Failed to create comment', error, {
70
+ ...params,
71
+ userId,
72
+ });
115
73
  }
116
74
  });
117
75
  router.get('/:resourceType/:resourceId/comments', async (req, res) => {
118
76
  const params = resourceParams(req, res);
119
77
  if (!params)
120
78
  return;
121
- const limit = queryLimit(req.query.limit);
122
- const offset = queryOffset(req.query.offset);
123
- const order = queryOrder(req.query.order);
124
79
  try {
125
- if (!(await canAccessCommentResource(params.resourceType, params.resourceId, 'read', viewerId(res)))) {
126
- notFound(res);
127
- return;
80
+ if (!(await canAccessCommentResource(params.resourceType, params.resourceId, 'read', getUserId(res) ?? undefined))) {
81
+ return sendNotFound(res);
128
82
  }
129
- res.json(await getCommentsByResource(params.resourceType, params.resourceId, { limit, offset, order }));
83
+ res.json(await getCommentsByResource(params.resourceType, params.resourceId, {
84
+ limit: queryLimit(req.query.limit) ?? 20,
85
+ offset: queryOffset(req.query.offset) ?? 0,
86
+ order: queryOrder(req.query.order),
87
+ }));
130
88
  }
131
89
  catch (error) {
132
- logger.error('Failed to list comments', { ...params, error });
133
- errorResponse(res, 500, 'comment.error.listFailed', 'Failed to list comments');
90
+ sendServerError(res, 'comment.error.listFailed', 'Failed to list comments', error, params);
134
91
  }
135
92
  });
136
93
  router.get('/:resourceType/:resourceId/comments/count', async (req, res) => {
@@ -138,118 +95,100 @@ router.get('/:resourceType/:resourceId/comments/count', async (req, res) => {
138
95
  if (!params)
139
96
  return;
140
97
  try {
141
- if (!(await canAccessCommentResource(params.resourceType, params.resourceId, 'read', viewerId(res)))) {
142
- notFound(res);
143
- return;
98
+ if (!(await canAccessCommentResource(params.resourceType, params.resourceId, 'read', getUserId(res) ?? undefined))) {
99
+ return sendNotFound(res);
144
100
  }
145
101
  const count = await getCommentCount(params.resourceType, params.resourceId);
146
102
  res.json({ count });
147
103
  }
148
104
  catch (error) {
149
- logger.error('Failed to count comments', { ...params, error });
150
- errorResponse(res, 500, 'comment.error.countFailed', 'Failed to count comments');
105
+ sendServerError(res, 'comment.error.countFailed', 'Failed to count comments', error, params);
151
106
  }
152
107
  });
153
108
  router.get('/comments/:commentId', async (req, res) => {
154
- const commentId = paramString(req.params.commentId);
155
- if (!commentId) {
156
- errorResponse(res, 400, 'comment.error.missingId', 'Comment ID is required');
157
- return;
158
- }
109
+ const commentId = queryString(req.params.commentId);
110
+ if (!commentId)
111
+ return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required');
159
112
  try {
160
113
  const comment = await getCommentById(commentId);
161
- if (!comment) {
162
- notFound(res);
163
- return;
164
- }
165
- if (!(await canAccessCommentResource(comment.resourceType, comment.resourceId, 'read', viewerId(res)))) {
166
- notFound(res);
167
- return;
114
+ if (!comment)
115
+ return sendNotFound(res);
116
+ if (!(await canAccessCommentResource(comment.resourceType, comment.resourceId, 'read', getUserId(res) ?? undefined))) {
117
+ return sendNotFound(res);
168
118
  }
169
119
  res.json(comment);
170
120
  }
171
121
  catch (error) {
172
- logger.error('Failed to read comment', { commentId, error });
173
- errorResponse(res, 500, 'comment.error.readFailed', 'Failed to read comment');
122
+ sendServerError(res, 'comment.error.readFailed', 'Failed to read comment', error, { commentId });
174
123
  }
175
124
  });
176
125
  router.put('/comments/:commentId', async (req, res) => {
177
- const userId = viewerId(res);
178
- if (!userId) {
179
- unauthorized(res);
180
- return;
181
- }
182
- const commentId = paramString(req.params.commentId);
183
- if (!commentId) {
184
- errorResponse(res, 400, 'comment.error.missingId', 'Comment ID is required');
185
- return;
186
- }
126
+ const userId = getUserId(res);
127
+ if (!userId)
128
+ return sendUnauthorized(res);
129
+ const commentId = queryString(req.params.commentId);
130
+ if (!commentId)
131
+ return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required');
187
132
  const parsed = updateCommentSchema.safeParse(req.body);
188
133
  if (!parsed.success) {
189
- invalid(res, parsed.error.issues);
190
- return;
134
+ return sendValidationError(res, 'comment.error.validationFailed', parsed.error.issues);
191
135
  }
192
136
  try {
193
137
  const updated = await updateComment(commentId, userId, parsed.data);
194
138
  if (!updated) {
195
- errorResponse(res, 404, 'comment.error.notFoundOrForbidden', 'Comment not found or not owned by user');
196
- return;
139
+ return sendError(res, 404, 'comment.error.notFoundOrForbidden', 'Comment not found or not owned by user');
197
140
  }
198
141
  res.json(updated);
199
142
  }
200
143
  catch (error) {
201
- logger.error('Failed to update comment', { commentId, userId, error });
202
- errorResponse(res, 500, 'comment.error.updateFailed', 'Failed to update comment');
144
+ sendServerError(res, 'comment.error.updateFailed', 'Failed to update comment', error, {
145
+ commentId,
146
+ userId,
147
+ });
203
148
  }
204
149
  });
205
150
  router.delete('/comments/:commentId', async (req, res) => {
206
- const userId = viewerId(res);
207
- if (!userId) {
208
- unauthorized(res);
209
- return;
210
- }
211
- const commentId = paramString(req.params.commentId);
212
- if (!commentId) {
213
- errorResponse(res, 400, 'comment.error.missingId', 'Comment ID is required');
214
- return;
215
- }
151
+ const userId = getUserId(res);
152
+ if (!userId)
153
+ return sendUnauthorized(res);
154
+ const commentId = queryString(req.params.commentId);
155
+ if (!commentId)
156
+ return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required');
216
157
  try {
217
158
  const deleted = await deleteComment(commentId, userId);
218
159
  if (!deleted) {
219
- errorResponse(res, 404, 'comment.error.notFoundOrForbidden', 'Comment not found or not owned by user');
220
- return;
160
+ return sendError(res, 404, 'comment.error.notFoundOrForbidden', 'Comment not found or not owned by user');
221
161
  }
222
162
  res.status(204).end();
223
163
  }
224
164
  catch (error) {
225
- logger.error('Failed to delete comment', { commentId, userId, error });
226
- errorResponse(res, 500, 'comment.error.deleteFailed', 'Failed to delete comment');
165
+ sendServerError(res, 'comment.error.deleteFailed', 'Failed to delete comment', error, {
166
+ commentId,
167
+ userId,
168
+ });
227
169
  }
228
170
  });
229
171
  router.get('/comments/:commentId/replies', async (req, res) => {
230
- const commentId = paramString(req.params.commentId);
231
- if (!commentId) {
232
- errorResponse(res, 400, 'comment.error.missingId', 'Comment ID is required');
233
- return;
234
- }
235
- const limit = queryLimit(req.query.limit);
236
- const offset = queryOffset(req.query.offset);
237
- const order = queryOrder(req.query.order);
172
+ const commentId = queryString(req.params.commentId);
173
+ if (!commentId)
174
+ return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required');
238
175
  try {
239
176
  const parent = await getCommentById(commentId);
240
- if (!parent) {
241
- notFound(res);
242
- return;
243
- }
244
- if (!(await canAccessCommentResource(parent.resourceType, parent.resourceId, 'read', viewerId(res)))) {
245
- notFound(res);
246
- return;
177
+ if (!parent)
178
+ return sendNotFound(res);
179
+ if (!(await canAccessCommentResource(parent.resourceType, parent.resourceId, 'read', getUserId(res) ?? undefined))) {
180
+ return sendNotFound(res);
247
181
  }
248
- res.json(await getReplies(commentId, { limit, offset, order }));
182
+ res.json(await getReplies(commentId, {
183
+ limit: queryLimit(req.query.limit) ?? 20,
184
+ offset: queryOffset(req.query.offset) ?? 0,
185
+ order: queryOrder(req.query.order),
186
+ }));
249
187
  }
250
188
  catch (error) {
251
- logger.error('Failed to list replies', { commentId, error });
252
- errorResponse(res, 500, 'comment.error.repliesFailed', 'Failed to list replies');
189
+ sendServerError(res, 'comment.error.repliesFailed', 'Failed to list replies', error, {
190
+ commentId,
191
+ });
253
192
  }
254
193
  });
255
194
  export default router;
package/dist/service.d.ts CHANGED
@@ -30,7 +30,7 @@ import type { Comment, CreateCommentInput, PaginatedResult, PaginationOptions, U
30
30
  * @throws {Error} When the comment could not be numbered; the comment row is
31
31
  * removed again so the caller is not told a create failed while it exists.
32
32
  */
33
- export declare function createComment(resourceType: string, resourceId: string, userId: string, data: CreateCommentInput): Promise<NumberedComment>;
33
+ export declare function createComment(resourceType: string, resourceId: string, userId: string | null, data: CreateCommentInput): Promise<NumberedComment>;
34
34
  /**
35
35
  * Retrieves paginated comments for a resource, ordered by creation date descending.
36
36
  * Only returns top-level comments (no replies).
@@ -1 +1 @@
1
- {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAqBH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AACnD,OAAO,KAAK,EACV,OAAO,EAEP,kBAAkB,EAClB,eAAe,EACf,iBAAiB,EACjB,kBAAkB,EACnB,MAAM,YAAY,CAAA;AAqCnB;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,aAAa,CACjC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,kBAAkB,GACvB,OAAO,CAAC,eAAe,CAAC,CAoE1B;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,qBAAqB,CACzC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,OAAO,GAAE,iBAAsB,GAC9B,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC,C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ClB,OAAO,GAAE,iBAAsB,GAC9B,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,CAsBnC;AAED;;;;;;GAMG;AACH,wBAAsB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAK/E;AAED;;;;;;;;GAQG;AACH,wBAAsB,aAAa,CACjC,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,kBAAkB,GACvB,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAgBzB;AAED;;;;;;;;GAQG;AACH,wBAAsB,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAMvF;AAED;;;;;;;GAOG;AACH,wBAAsB,UAAU,CAC9B,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,iBAAsB,GAC9B,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,CAkBnC;AAED;;;;;;GAMG;AACH,wBAAsB,eAAe,CAAC,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAK/F"}
package/dist/service.js CHANGED
@@ -18,12 +18,17 @@ async function withAuthors(comments) {
18
18
  const loader = globalThis[PUBLIC_PROFILES_KEY];
19
19
  if (!loader)
20
20
  return comments;
21
+ const userIds = comments
22
+ .map((comment) => comment.userId)
23
+ .filter((id) => Boolean(id));
24
+ if (userIds.length === 0)
25
+ return comments;
21
26
  try {
22
- const profiles = await loader(comments.map((comment) => comment.userId));
27
+ const profiles = await loader(userIds);
23
28
  if (profiles.size === 0)
24
29
  return comments;
25
30
  return comments.map((comment) => {
26
- const author = profiles.get(comment.userId);
31
+ const author = comment.userId ? profiles.get(comment.userId) : undefined;
27
32
  return author ? { ...comment, author } : comment;
28
33
  });
29
34
  }
@@ -64,6 +69,14 @@ async function withNumbers(comments) {
64
69
  * removed again so the caller is not told a create failed while it exists.
65
70
  */
66
71
  export async function createComment(resourceType, resourceId, userId, data) {
72
+ const trimmedBody = data.body.trim();
73
+ if (!trimmedBody) {
74
+ throw new Error('Comment body is required');
75
+ }
76
+ const guestName = userId ? null : (data.authorName?.trim() ?? '');
77
+ if (!userId && !guestName) {
78
+ throw new Error('Author name is required for guest comments');
79
+ }
67
80
  const hasPolicies = hasResourceAccessPolicies();
68
81
  const policy = getResourceAccessPolicy(resourceType);
69
82
  const execute = async () => {
@@ -85,8 +98,9 @@ export async function createComment(resourceType, resourceId, userId, data) {
85
98
  resourceType,
86
99
  resourceId,
87
100
  userId,
101
+ ...(guestName ? { authorName: guestName } : {}),
88
102
  parentId: data.parentId ?? null,
89
- body: data.body,
103
+ body: trimmedBody,
90
104
  editedAt: null,
91
105
  });
92
106
  const comment = result.data;
@@ -183,10 +197,10 @@ export async function getCommentById(commentId) {
183
197
  */
184
198
  export async function updateComment(commentId, userId, data) {
185
199
  const existing = await findById(TABLE, commentId);
186
- if (!existing || existing.userId !== userId)
200
+ if (!existing || !existing.userId || existing.userId !== userId)
187
201
  return null;
188
202
  const result = await updateById(TABLE, commentId, {
189
- body: data.body,
203
+ body: data.body.trim(),
190
204
  editedAt: new Date().toISOString(),
191
205
  // Strictly later than the last write: an edit in the same millisecond as the create
192
206
  // still shows a changed updatedAt.
@@ -208,7 +222,7 @@ export async function updateComment(commentId, userId, data) {
208
222
  */
209
223
  export async function deleteComment(commentId, userId) {
210
224
  const existing = await findById(TABLE, commentId);
211
- if (!existing || existing.userId !== userId)
225
+ if (!existing || !existing.userId || existing.userId !== userId)
212
226
  return false;
213
227
  await deleteById(TABLE, commentId);
214
228
  return true;
package/dist/types.d.ts CHANGED
@@ -31,8 +31,10 @@ export interface Comment {
31
31
  resourceType: string;
32
32
  /** The ID of the resource this comment is attached to. */
33
33
  resourceId: string;
34
- /** The ID of the user who created this comment. */
35
- userId: string;
34
+ /** The ID of the user who created this comment, or `null` for guest comments. */
35
+ userId: string | null;
36
+ /** Display name supplied for a guest comment, or `null` for authenticated comments. */
37
+ authorName?: string | null;
36
38
  /** Hydrated public author profile when `@molecule/api-resource-user` is loaded. */
37
39
  author?: CommentAuthor | null;
38
40
  /** The parent comment ID for threaded replies, or `null` for top-level comments. */
@@ -54,6 +56,8 @@ export interface CreateCommentInput {
54
56
  body: string;
55
57
  /** Optional parent comment ID for threaded replies. */
56
58
  parentId?: string;
59
+ /** Display name when posting as an unauthenticated guest (ignored when signed in). */
60
+ authorName?: string;
57
61
  }
58
62
  /**
59
63
  * Input for updating an existing comment.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,iGAAiG;AACjG,MAAM,WAAW,aAAa;IAC5B,+BAA+B;IAC/B,EAAE,EAAE,MAAM,CAAA;IACV,qCAAqC;IACrC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,yCAAyC;IACzC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;IACnB,sCAAsC;IACtC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAA;IAClB,uCAAuC;IACvC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,OAAO;IACtB,iCAAiC;IACjC,EAAE,EAAE,MAAM,CAAA;IACV,4FAA4F;IAC5F,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,iFAAiF;IACjF,YAAY,EAAE,MAAM,CAAA;IACpB,0DAA0D;IAC1D,UAAU,EAAE,MAAM,CAAA;IAClB,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAA;IACd,mFAAmF;IACnF,MAAM,CAAC,EAAE,aAAa,GAAG,IAAI,CAAA;IAC7B,oFAAoF;IACpF,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,6BAA6B;IAC7B,IAAI,EAAE,MAAM,CAAA;IACZ,mEAAmE;IACnE,QAAQ,EAAE,MAAM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MAAM,CAAA;IACb,0CAA0C;IAC1C,KAAK,EAAE,MAAM,CAAA;IACb,iCAAiC;IACjC,MAAM,EAAE,MAAM,CAAA;CACf"}
@@ -10,6 +10,7 @@ import { z } from 'zod';
10
10
  export declare const createCommentSchema: z.ZodObject<{
11
11
  body: z.ZodString;
12
12
  parentId: z.ZodOptional<z.ZodString>;
13
+ authorName: z.ZodOptional<z.ZodString>;
13
14
  }, z.core.$strip>;
14
15
  /**
15
16
  * Schema for validating comment update input.
@@ -1 +1 @@
1
- {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB;;GAEG;AACH,eAAO,MAAM,mBAAmB;;;iBAK9B,CAAA;AAEF;;GAEG;AACH,eAAO,MAAM,mBAAmB;;iBAG9B,CAAA"}
1
+ {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB;;GAEG;AACH,eAAO,MAAM,mBAAmB;;;;iBAO9B,CAAA;AAEF;;GAEG;AACH,eAAO,MAAM,mBAAmB;;iBAG9B,CAAA"}
@@ -8,15 +8,17 @@ import { z } from 'zod';
8
8
  * Schema for validating comment creation input.
9
9
  */
10
10
  export const createCommentSchema = z.object({
11
- /** The comment body text. Must be non-empty and at most 10,000 characters. */
12
- body: z.string().min(1).max(10_000),
11
+ /** The comment body text. Must be non-empty after trimming and at most 10,000 characters. */
12
+ body: z.string().trim().min(1).max(10_000),
13
13
  /** Optional parent comment ID for threaded replies. */
14
14
  parentId: z.string().uuid().optional(),
15
+ /** Display name for guest comments (ignored when authenticated to prevent spoofing). */
16
+ authorName: z.string().trim().min(1).max(120).optional(),
15
17
  });
16
18
  /**
17
19
  * Schema for validating comment update input.
18
20
  */
19
21
  export const updateCommentSchema = z.object({
20
- /** The updated comment body text. Must be non-empty and at most 10,000 characters. */
21
- body: z.string().min(1).max(10_000),
22
+ /** The updated comment body text. Must be non-empty after trimming and at most 10,000 characters. */
23
+ body: z.string().trim().min(1).max(10_000),
22
24
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/api-resource-comment",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Threaded comments on any resource with polymorphic attachment, pagination and sequential integer comment numbers (createNumberedComment)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -45,15 +45,10 @@
45
45
  "@molecule/api-i18n": "^1.0.1",
46
46
  "@molecule/api-logger": "^1.0.1",
47
47
  "@molecule/api-rate-limit": "^1.0.1",
48
- "@molecule/api-resource": "^1.0.1",
48
+ "@molecule/api-resource": "^1.4.0",
49
49
  "express": "^5.0.0",
50
50
  "zod": "^4.0.0"
51
51
  },
52
- "peerDependenciesMeta": {
53
- "@molecule/api-resource": {
54
- "optional": true
55
- }
56
- },
57
52
  "repository": {
58
53
  "type": "git",
59
54
  "url": "https://github.com/molecule-dev/molecule.git",
@@ -2,7 +2,8 @@ CREATE TABLE IF NOT EXISTS "comments" (
2
2
  "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
3
3
  "resourceType" VARCHAR(255) NOT NULL,
4
4
  "resourceId" VARCHAR(255) NOT NULL,
5
- "userId" UUID NOT NULL,
5
+ "userId" UUID,
6
+ "authorName" VARCHAR(120),
6
7
  "parentId" UUID REFERENCES "comments"("id") ON DELETE CASCADE,
7
8
  "body" TEXT NOT NULL,
8
9
  "editedAt" TIMESTAMPTZ,
@@ -10,7 +11,6 @@ CREATE TABLE IF NOT EXISTS "comments" (
10
11
  "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT now()
11
12
  );
12
13
 
13
- CREATE INDEX IF NOT EXISTS "idx_comments_resource" ON "comments" ("resourceType", "resourceId");
14
14
  CREATE INDEX IF NOT EXISTS "idx_comments_resource_created" ON "comments" ("resourceType", "resourceId", "createdAt");
15
15
  CREATE INDEX IF NOT EXISTS "idx_comments_parent" ON "comments" ("parentId");
16
16
  CREATE INDEX IF NOT EXISTS "idx_comments_user" ON "comments" ("userId");
@@ -1,11 +1,20 @@
1
1
  import { type NextFunction, type Request, type Response, Router } from 'express'
2
2
 
3
- import { t } from '@molecule/api-i18n'
4
- import { logger } from '@molecule/api-logger'
5
3
  import {
6
4
  consume as consumeRateLimit,
7
5
  hasProvider as hasRateLimitProvider,
8
6
  } from '@molecule/api-rate-limit'
7
+ import {
8
+ getUserId,
9
+ queryLimit,
10
+ queryOffset,
11
+ queryString,
12
+ sendError,
13
+ sendNotFound,
14
+ sendServerError,
15
+ sendUnauthorized,
16
+ sendValidationError,
17
+ } from '@molecule/api-resource'
9
18
  import {
10
19
  canAccessCommentResource,
11
20
  CommentResourceAccessError,
@@ -25,69 +34,16 @@ import {
25
34
  // Fail-closed access: once any sibling resource registers a policy via
26
35
  // registerResourceAccessPolicy() (e.g. articles.ts), unregistered resourceTypes
27
36
  // and private/draft parents are refused with 404.
28
- const router = Router()
29
-
30
- /** Maximum page size accepted by comment listing endpoints. */
31
- const MAX_LIST_LIMIT = 100
32
- /** Valid slug pattern for polymorphic `resourceType` path segments. */
37
+ // Set ALLOW_GUEST_COMMENTS = true on public sites (e.g. blogs) so unauthenticated
38
+ // readers may post comments by supplying `authorName` (rate-limited; signed-in
39
+ // users always post under their account to prevent spoofing).
40
+ const ALLOW_GUEST_COMMENTS = false
33
41
  const RESOURCE_TYPE_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/i
34
-
35
- /** Read the authenticated session user ID without type casts. */
36
- function viewerId(res: Response): string | undefined {
37
- const session: unknown = res.locals.session
38
- if (typeof session !== 'object' || session === null || !('userId' in session)) return undefined
39
- return typeof session.userId === 'string' && session.userId ? session.userId : undefined
40
- }
41
-
42
- /** Read a single string route param. */
43
- function paramString(value: unknown): string | undefined {
44
- return typeof value === 'string' && value.trim() ? value : undefined
45
- }
46
-
47
- /** Read an optional bounded page size (`1..MAX_LIST_LIMIT`). */
48
- function queryLimit(value: unknown): number {
49
- const parsed = parseInt(String(value ?? ''), 10)
50
- return Number.isFinite(parsed) ? Math.min(MAX_LIST_LIMIT, Math.max(1, parsed)) : 20
51
- }
52
-
53
- /** Read an optional non-negative pagination offset. */
54
- function queryOffset(value: unknown): number {
55
- const parsed = parseInt(String(value ?? ''), 10)
56
- return Number.isFinite(parsed) ? Math.max(0, parsed) : 0
57
- }
42
+ const router = Router()
58
43
 
59
44
  /** Read an optional sort direction (`'asc'` or `'desc'`). */
60
45
  function queryOrder(value: unknown): 'asc' | 'desc' | undefined {
61
- if (value === 'asc' || value === 'desc') return value
62
- return undefined
63
- }
64
-
65
- /** Send an i18n-formatted error response. */
66
- function errorResponse(res: Response, status: number, key: string, fallback: string): void {
67
- res.status(status).json({ error: t(key, undefined, { defaultValue: fallback }), errorKey: key })
68
- }
69
-
70
- /** Answer a request missing a valid signed-in session. */
71
- function unauthorized(res: Response): void {
72
- errorResponse(res, 401, 'resource.error.unauthorized', 'Unauthorized.')
73
- }
74
-
75
- /** Answer a request for a missing or inaccessible comment or parent resource. */
76
- function notFound(res: Response): void {
77
- errorResponse(res, 404, 'resource.error.notFound', 'Not found.')
78
- }
79
-
80
- /** Answer a request with invalid input fields. */
81
- function invalid(
82
- res: Response,
83
- issues: ReadonlyArray<{ path: PropertyKey[]; message: string }>,
84
- ): void {
85
- res.status(400).json({
86
- error: issues
87
- .map((issue) => `${issue.path.map(String).join('.')}: ${issue.message}`)
88
- .join(', '),
89
- errorKey: 'comment.error.validationFailed',
90
- })
46
+ return value === 'asc' || value === 'desc' ? value : undefined
91
47
  }
92
48
 
93
49
  /** Validate `resourceType` and `resourceId` path params. */
@@ -95,10 +51,10 @@ function resourceParams(
95
51
  req: Request,
96
52
  res: Response,
97
53
  ): { resourceType: string; resourceId: string } | null {
98
- const resourceType = paramString(req.params.resourceType)
99
- const resourceId = paramString(req.params.resourceId)
54
+ const resourceType = queryString(req.params.resourceType)
55
+ const resourceId = queryString(req.params.resourceId)
100
56
  if (!resourceType || !resourceId || !RESOURCE_TYPE_PATTERN.test(resourceType)) {
101
- errorResponse(res, 400, 'comment.error.missingResource', 'Resource type and ID are required')
57
+ sendError(res, 400, 'comment.error.missingResource', 'Resource type and ID are required')
102
58
  return null
103
59
  }
104
60
  return { resourceType, resourceId }
@@ -110,13 +66,13 @@ async function rateLimitComments(req: Request, res: Response, next: NextFunction
110
66
  next()
111
67
  return
112
68
  }
113
- const key = `comments:create:${viewerId(res) ?? req.ip ?? 'unknown'}`
69
+ const key = `comments:create:${getUserId(res) ?? req.ip ?? 'unknown'}`
114
70
  const result = await consumeRateLimit(key)
115
71
  if (!result.allowed) {
116
72
  const retryAfter =
117
73
  result.retryAfter ?? Math.max(1, Math.ceil((result.resetAt.getTime() - Date.now()) / 1000))
118
74
  res.set('Retry-After', String(retryAfter))
119
- errorResponse(
75
+ sendError(
120
76
  res,
121
77
  429,
122
78
  'rateLimit.error.tooManyRequests',
@@ -128,215 +84,181 @@ async function rateLimitComments(req: Request, res: Response, next: NextFunction
128
84
  }
129
85
 
130
86
  router.post('/:resourceType/:resourceId/comments', rateLimitComments, async (req, res) => {
131
- const userId = viewerId(res)
132
- if (!userId) {
133
- unauthorized(res)
134
- return
135
- }
87
+ const userId = getUserId(res)
88
+ if (!userId && !ALLOW_GUEST_COMMENTS) return sendUnauthorized(res)
136
89
  const params = resourceParams(req, res)
137
90
  if (!params) return
138
91
 
139
92
  const parsed = createCommentSchema.safeParse(req.body)
140
93
  if (!parsed.success) {
141
- invalid(res, parsed.error.issues)
142
- return
94
+ return sendValidationError(res, 'comment.error.validationFailed', parsed.error.issues)
95
+ }
96
+ if (!userId && !parsed.data.authorName) {
97
+ return sendValidationError(res, 'comment.error.validationFailed', [
98
+ { path: ['authorName'], message: 'Name is required' },
99
+ ])
143
100
  }
144
101
 
145
102
  try {
146
103
  const comment = await createComment(params.resourceType, params.resourceId, userId, parsed.data)
147
104
  res.status(201).json(comment)
148
105
  } catch (error) {
149
- if (error instanceof CommentResourceAccessError) {
150
- notFound(res)
151
- return
152
- }
153
- logger.error('Failed to create comment', { ...params, userId, error })
154
- errorResponse(res, 500, 'comment.error.createFailed', 'Failed to create comment')
106
+ if (error instanceof CommentResourceAccessError) return sendNotFound(res)
107
+ sendServerError(res, 'comment.error.createFailed', 'Failed to create comment', error, {
108
+ ...params,
109
+ userId,
110
+ })
155
111
  }
156
112
  })
157
113
 
158
114
  router.get('/:resourceType/:resourceId/comments', async (req, res) => {
159
115
  const params = resourceParams(req, res)
160
116
  if (!params) return
161
-
162
- const limit = queryLimit(req.query.limit)
163
- const offset = queryOffset(req.query.offset)
164
- const order = queryOrder(req.query.order)
165
-
166
117
  try {
167
118
  if (
168
119
  !(await canAccessCommentResource(
169
120
  params.resourceType,
170
121
  params.resourceId,
171
122
  'read',
172
- viewerId(res),
123
+ getUserId(res) ?? undefined,
173
124
  ))
174
125
  ) {
175
- notFound(res)
176
- return
126
+ return sendNotFound(res)
177
127
  }
178
128
  res.json(
179
- await getCommentsByResource(params.resourceType, params.resourceId, { limit, offset, order }),
129
+ await getCommentsByResource(params.resourceType, params.resourceId, {
130
+ limit: queryLimit(req.query.limit) ?? 20,
131
+ offset: queryOffset(req.query.offset) ?? 0,
132
+ order: queryOrder(req.query.order),
133
+ }),
180
134
  )
181
135
  } catch (error) {
182
- logger.error('Failed to list comments', { ...params, error })
183
- errorResponse(res, 500, 'comment.error.listFailed', 'Failed to list comments')
136
+ sendServerError(res, 'comment.error.listFailed', 'Failed to list comments', error, params)
184
137
  }
185
138
  })
186
139
 
187
140
  router.get('/:resourceType/:resourceId/comments/count', async (req, res) => {
188
141
  const params = resourceParams(req, res)
189
142
  if (!params) return
190
-
191
143
  try {
192
144
  if (
193
145
  !(await canAccessCommentResource(
194
146
  params.resourceType,
195
147
  params.resourceId,
196
148
  'read',
197
- viewerId(res),
149
+ getUserId(res) ?? undefined,
198
150
  ))
199
151
  ) {
200
- notFound(res)
201
- return
152
+ return sendNotFound(res)
202
153
  }
203
154
  const count = await getCommentCount(params.resourceType, params.resourceId)
204
155
  res.json({ count })
205
156
  } catch (error) {
206
- logger.error('Failed to count comments', { ...params, error })
207
- errorResponse(res, 500, 'comment.error.countFailed', 'Failed to count comments')
157
+ sendServerError(res, 'comment.error.countFailed', 'Failed to count comments', error, params)
208
158
  }
209
159
  })
210
160
 
211
161
  router.get('/comments/:commentId', async (req, res) => {
212
- const commentId = paramString(req.params.commentId)
213
- if (!commentId) {
214
- errorResponse(res, 400, 'comment.error.missingId', 'Comment ID is required')
215
- return
216
- }
217
-
162
+ const commentId = queryString(req.params.commentId)
163
+ if (!commentId) return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required')
218
164
  try {
219
165
  const comment = await getCommentById(commentId)
220
- if (!comment) {
221
- notFound(res)
222
- return
223
- }
166
+ if (!comment) return sendNotFound(res)
224
167
  if (
225
168
  !(await canAccessCommentResource(
226
169
  comment.resourceType,
227
170
  comment.resourceId,
228
171
  'read',
229
- viewerId(res),
172
+ getUserId(res) ?? undefined,
230
173
  ))
231
174
  ) {
232
- notFound(res)
233
- return
175
+ return sendNotFound(res)
234
176
  }
235
177
  res.json(comment)
236
178
  } catch (error) {
237
- logger.error('Failed to read comment', { commentId, error })
238
- errorResponse(res, 500, 'comment.error.readFailed', 'Failed to read comment')
179
+ sendServerError(res, 'comment.error.readFailed', 'Failed to read comment', error, { commentId })
239
180
  }
240
181
  })
241
182
 
242
183
  router.put('/comments/:commentId', async (req, res) => {
243
- const userId = viewerId(res)
244
- if (!userId) {
245
- unauthorized(res)
246
- return
247
- }
248
- const commentId = paramString(req.params.commentId)
249
- if (!commentId) {
250
- errorResponse(res, 400, 'comment.error.missingId', 'Comment ID is required')
251
- return
252
- }
253
-
184
+ const userId = getUserId(res)
185
+ if (!userId) return sendUnauthorized(res)
186
+ const commentId = queryString(req.params.commentId)
187
+ if (!commentId) return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required')
254
188
  const parsed = updateCommentSchema.safeParse(req.body)
255
189
  if (!parsed.success) {
256
- invalid(res, parsed.error.issues)
257
- return
190
+ return sendValidationError(res, 'comment.error.validationFailed', parsed.error.issues)
258
191
  }
259
-
260
192
  try {
261
193
  const updated = await updateComment(commentId, userId, parsed.data)
262
194
  if (!updated) {
263
- errorResponse(
195
+ return sendError(
264
196
  res,
265
197
  404,
266
198
  'comment.error.notFoundOrForbidden',
267
199
  'Comment not found or not owned by user',
268
200
  )
269
- return
270
201
  }
271
202
  res.json(updated)
272
203
  } catch (error) {
273
- logger.error('Failed to update comment', { commentId, userId, error })
274
- errorResponse(res, 500, 'comment.error.updateFailed', 'Failed to update comment')
204
+ sendServerError(res, 'comment.error.updateFailed', 'Failed to update comment', error, {
205
+ commentId,
206
+ userId,
207
+ })
275
208
  }
276
209
  })
277
210
 
278
211
  router.delete('/comments/:commentId', async (req, res) => {
279
- const userId = viewerId(res)
280
- if (!userId) {
281
- unauthorized(res)
282
- return
283
- }
284
- const commentId = paramString(req.params.commentId)
285
- if (!commentId) {
286
- errorResponse(res, 400, 'comment.error.missingId', 'Comment ID is required')
287
- return
288
- }
289
-
212
+ const userId = getUserId(res)
213
+ if (!userId) return sendUnauthorized(res)
214
+ const commentId = queryString(req.params.commentId)
215
+ if (!commentId) return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required')
290
216
  try {
291
217
  const deleted = await deleteComment(commentId, userId)
292
218
  if (!deleted) {
293
- errorResponse(
219
+ return sendError(
294
220
  res,
295
221
  404,
296
222
  'comment.error.notFoundOrForbidden',
297
223
  'Comment not found or not owned by user',
298
224
  )
299
- return
300
225
  }
301
226
  res.status(204).end()
302
227
  } catch (error) {
303
- logger.error('Failed to delete comment', { commentId, userId, error })
304
- errorResponse(res, 500, 'comment.error.deleteFailed', 'Failed to delete comment')
228
+ sendServerError(res, 'comment.error.deleteFailed', 'Failed to delete comment', error, {
229
+ commentId,
230
+ userId,
231
+ })
305
232
  }
306
233
  })
307
234
 
308
235
  router.get('/comments/:commentId/replies', async (req, res) => {
309
- const commentId = paramString(req.params.commentId)
310
- if (!commentId) {
311
- errorResponse(res, 400, 'comment.error.missingId', 'Comment ID is required')
312
- return
313
- }
314
-
315
- const limit = queryLimit(req.query.limit)
316
- const offset = queryOffset(req.query.offset)
317
- const order = queryOrder(req.query.order)
318
-
236
+ const commentId = queryString(req.params.commentId)
237
+ if (!commentId) return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required')
319
238
  try {
320
239
  const parent = await getCommentById(commentId)
321
- if (!parent) {
322
- notFound(res)
323
- return
324
- }
240
+ if (!parent) return sendNotFound(res)
325
241
  if (
326
242
  !(await canAccessCommentResource(
327
243
  parent.resourceType,
328
244
  parent.resourceId,
329
245
  'read',
330
- viewerId(res),
246
+ getUserId(res) ?? undefined,
331
247
  ))
332
248
  ) {
333
- notFound(res)
334
- return
249
+ return sendNotFound(res)
335
250
  }
336
- res.json(await getReplies(commentId, { limit, offset, order }))
251
+ res.json(
252
+ await getReplies(commentId, {
253
+ limit: queryLimit(req.query.limit) ?? 20,
254
+ offset: queryOffset(req.query.offset) ?? 0,
255
+ order: queryOrder(req.query.order),
256
+ }),
257
+ )
337
258
  } catch (error) {
338
- logger.error('Failed to list replies', { commentId, error })
339
- errorResponse(res, 500, 'comment.error.repliesFailed', 'Failed to list replies')
259
+ sendServerError(res, 'comment.error.repliesFailed', 'Failed to list replies', error, {
260
+ commentId,
261
+ })
340
262
  }
341
263
  })
342
264