@molecule/api-resource-comment

API resource · comments · API (Node) · v1.7.0 · Apache-2.0

Threaded comments on any resource with polymorphic attachment, pagination and sequential integer comment numbers (createNumberedComment)

npm install @molecule/api-resource-comment

npm · Source on GitHub

How it works

@molecule/api-resource-comment is an API resource: the routes, validation and storage for comments, built on the database and auth cores so it runs on whichever providers your app has bonded.

import { routes, requestHandlerMap } from '@molecule/api-resource-comment'

// Wire routes into your Express app via mlcl inject
// POST   /:resourceType/:resourceId/comments
// GET    /:resourceType/:resourceId/comments
// GET    /comments/:commentId
// PUT    /comments/:commentId
// DELETE /comments/:commentId
// GET    /comments/:commentId/replies
// GET    /:resourceType/:resourceId/comments/count — cheap badge counts

Works with: @molecule/api-database, @molecule/api-i18n, @molecule/api-logger, @molecule/api-rate-limit, @molecule/api-resource

Live demos

Running apps built with Molecule that install this package — open the app or study the template.

Reference

Threaded comments resource for molecule.dev.

Polymorphic comments that attach to any resource type. Supports threaded replies, pagination, and ownership-based authorization.

Tables this package owns: comments and comment_numbers. A comment row is found by its comments.id (a UUID); comment_numbers gives it the sequential integer many clients address it by, and the join between the two is comment_numbers.commentId = comments.id (declared FK, ON DELETE CASCADE) — one row per comment created through this package, never a mapping table of your own.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { routes, requestHandlerMap } from '@molecule/api-resource-comment'

// Wire routes into your Express app via mlcl inject
// POST   /:resourceType/:resourceId/comments
// GET    /:resourceType/:resourceId/comments
// GET    /comments/:commentId
// PUT    /comments/:commentId
// DELETE /comments/:commentId
// GET    /comments/:commentId/replies
// GET    /:resourceType/:resourceId/comments/count — cheap badge counts

Type

resource

Installation

npm install @molecule/api-resource-comment @molecule/api-database @molecule/api-i18n @molecule/api-logger @molecule/api-rate-limit @molecule/api-resource express zod
npm install -D @types/express

API

Interfaces

CommentResourceAccessContext

Context passed to a registered parent-resource access policy.

interface CommentResourceAccessContext {
  /** The polymorphic parent resource type (e.g. `'article'`, `'post'`, `'project'`). */
  resourceType: string
  /** The polymorphic parent resource identifier. */
  resourceId: string
  /**
   * Whether the caller is reading comments (`'read'`), posting a new comment (`'create'`),
   * or moderating/deleting another user's or guest's comment (`'moderate'`).
   */
  action: CommentResourceAction
  /** The signed-in user ID, or `null`/`undefined` for anonymous callers. */
  viewerId?: string | null
}

CommentAuthor

Public display profile attached to a comment when @molecule/api-resource-user is loaded.

interface CommentAuthor {
  /** The user's canonical id. */
  id: string
  /** The public username, when set. */
  username: string | null
  /** The public display name, when set. */
  name: string | null
  /** The public biography, when set. */
  bio: string | null
  /** The public avatar URL, when set. */
  avatar: string | null
}

Comment

A comment attached to a resource, with optional threading via parentId.

interface Comment {
  /** Unique comment identifier. */
  id: string
  /** Stable integer identity on creates and paginated reads; absent on unnumbered imports. */
  number?: number
  /** The type of resource this comment is attached to (e.g. 'project', 'post'). */
  resourceType: string
  /** The ID of the resource this comment is attached to. */
  resourceId: string
  /** The ID of the user who created this comment, or `null` for guest comments. */
  userId: string | null
  /** Display name supplied for a guest comment, or `null` for authenticated comments. */
  authorName?: string | null
  /** Hydrated public author profile when `@molecule/api-resource-user` is loaded. */
  author?: CommentAuthor | null
  /** The parent comment ID for threaded replies, or `null` for top-level comments. */
  parentId: string | null
  /** The comment body text. */
  body: string
  /** When the comment was last edited, or `null` if never edited. */
  editedAt: string | null
  /** When the comment was created (ISO 8601). */
  createdAt: string
  /** When the comment was last updated (ISO 8601). */
  updatedAt: string
}

CreateCommentInput

Input for creating a new comment.

interface CreateCommentInput {
  /** The comment body text. */
  body: string
  /** Optional parent comment ID for threaded replies. */
  parentId?: string
  /** Display name when posting as an unauthenticated guest (ignored when signed in). */
  authorName?: string
}

UpdateCommentInput

Input for updating an existing comment.

interface UpdateCommentInput {
  /** The updated comment body text. */
  body: string
}

PaginationOptions

Options for paginated queries.

interface PaginationOptions {
  /** Maximum number of results to return. */
  limit?: number
  /** Number of results to skip. */
  offset?: number
  /** Sort direction by creation time (`'asc'` or `'desc'`). */
  order?: 'asc' | 'desc'
}

PaginatedResult

A paginated result set.

interface PaginatedResult<T> {
  /** The result items for the current page. */
  data: T[]
  /** Total number of matching items across all pages. */
  total: number
  /** Maximum number of results per page. */
  limit: number
  /** Number of results skipped. */
  offset: number
}

Types

CommentResourceAction

The kind of comment operation requesting access to the parent resource.

type CommentResourceAction = 'read' | 'create' | 'moderate'

CommentResourceAccessCheck

Predicate deciding whether a viewer may read or create comments on a parent resource.

type CommentResourceAccessCheck = (
  context: CommentResourceAccessContext,
) => boolean | Promise<boolean>

NumberedComment

A comment together with its sequential number.

type NumberedComment = Comment & {
  /** The comment's sequential integer number (1, 2, 3, …). */
  number: number
}

Classes

CommentResourceAccessError

Thrown by createComment when a registered parent-resource access policy denies access. Handlers translate this to HTTP 404 so private or missing parents are not distinguished.

class CommentResourceAccessError extends Error {
  /** HTTP status code to return for a denied or missing parent resource. */
  readonly statusCode = 404
  /** Stable i18n error key matching `@molecule/api-resource`. */
  readonly errorKey = 'resource.error.notFound'
  /** The parent resource type that was denied. */
  readonly resourceType: string
  /** The parent resource identifier that was denied. */
  readonly resourceId: string

  /**
   * Creates an access-denied error for a comment's parent resource.
   *
   * @param resourceType - The parent resource type.
   * @param resourceId - The parent resource identifier.
   */
  constructor(resourceType: string, resourceId: string) {
    super(`Resource not accessible for comments: ${resourceType}/${resourceId}`)
    this.name = 'CommentResourceAccessError'
    this.resourceType = resourceType
    this.resourceId = resourceId
  }
}

Functions

registerResourceAccessPolicy(resourceType, check)

Registers a parent-resource access policy for resourceType (or '*' as a wildcard fallback for any resource type without a specific policy).

function registerResourceAccessPolicy(resourceType: string, check: CommentResourceAccessCheck): void
  • resourceType — Canonical resource type slug (e.g. 'article', 'project', '*').
  • check — Predicate returning true when the viewer may perform action.

unregisterResourceAccessPolicy(resourceType)

Removes a previously registered parent-resource access policy.

function unregisterResourceAccessPolicy(resourceType: string): void
  • resourceType — Canonical resource type slug to unregister.

clearResourceAccessPolicies()

Removes all registered parent-resource access policies. Intended for tests.

function clearResourceAccessPolicies(): void

getResourceAccessPolicy(resourceType)

Returns the access policy registered for resourceType, falling back to '*'.

function getResourceAccessPolicy(resourceType: string): CommentResourceAccessCheck | undefined
  • resourceType — Canonical resource type slug.

Returns: The matching policy predicate, or undefined when unrestricted.

hasResourceAccessPolicies()

Returns true when at least one parent-resource access policy is registered.

function hasResourceAccessPolicies(): boolean

Returns: Whether any access policy is active.

canAccessCommentResource(resourceType, resourceId, action, viewerId)

Evaluates the registered access policy for (resourceType, resourceId). When no policies are registered at all, returns true. Once any resource access policy is registered, unregistered resource types fail closed (false) unless a '*' wildcard policy explicitly allows them.

function canAccessCommentResource(
  resourceType: string,
  resourceId: string,
  action: CommentResourceAction,
  viewerId?: string | null,
): Promise<boolean>
  • resourceType — Canonical resource type slug.
  • resourceId — The parent resource identifier.
  • action — 'read' or 'create'.
  • viewerId — The signed-in viewer ID, or null/undefined for anonymous callers.

Returns: Whether access is permitted.

commentCount(req, res)

Returns the total comment count for a resource.

function commentCount(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
  • req — The request with resourceType and resourceId params.
  • res — The response object.

create(req, res)

Creates a new comment on a resource.

function create(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
  • req — The request with resourceType and resourceId params and comment body.
  • res — The response object.

del(req, res)

Deletes a comment. Only the comment owner can delete.

function del(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
  • req — The request with commentId param.
  • res — The response object.

list(req, res)

Lists paginated top-level comments for a resource.

function list(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
  • req — The request with resourceType and resourceId params.
  • res — The response object.

read(req, res)

Retrieves a single comment by ID.

function read(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
  • req — The request with commentId param.
  • res — The response object.

replies(req, res)

Lists paginated replies to a comment.

function replies(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
  • req — The request with commentId param.
  • res — The response object.

update(req, res)

Updates an existing comment. Only the comment owner can update.

function update(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
  • req — The request with commentId param and update body.
  • res — The response object.

numberComment(commentId)

The comment's number, allocating the next one when it has none. Numbers are unique and increase. Use it for a comment that was inserted into comments without createComment() — every comment created through this package is numbered already.

function numberComment(commentId: string): Promise<number>
  • commentId — The comment's UUID.

Returns: Its sequential number.

createNumberedComment(resourceType, resourceId, userId, data)

Creates a comment and its number together: both are written, or neither.

This is createComment() under the name an integer-id API reads best — it takes the same arguments and returns the same NumberedComment. Address the result by number and read it back with getCommentByNumber(number).

function createNumberedComment(
  resourceType: string,
  resourceId: string,
  userId: string | null,
  data: CreateCommentInput,
): Promise<NumberedComment>
  • resourceType — The type of resource being commented on.
  • resourceId — The ID of the resource being commented on.
  • userId — The ID of the commenting user.
  • data — The comment creation input.

Returns: The created comment with its number.

getCommentByNumber(number)

The comment a number belongs to — the lookup behind an integer-addressed route such as DELETE /comments/:id: find the comment here, then pass its id to deleteComment()/updateComment().

function getCommentByNumber(number: number): Promise<NumberedComment | null>
  • number — The comment's sequential number.

Returns: The comment with its number, or null when no comment has it.

commentNumbers(commentIds)

The numbers of the given comments, for listing them with their numbers.

Every comment created through this package is numbered, so a comment missing from the map was inserted directly into comments (or predates numbering by default); give it one with numberComment(id). Never read a missing entry as 0 — 0 is not a comment id, and an integer id of 0 cannot be found again.

function commentNumbers(commentIds: readonly string[]): Promise<Map<string, number>>
  • commentIds — The comments' UUIDs.

Returns: Each numbered comment's UUID mapped to its number.

createComment(resourceType, resourceId, userId, data)

Creates a new comment on a resource, with its sequential number.

The comment row and its comment_numbers row are written together: the returned comment carries number (1, 2, 3, …) beside its UUID id. An API whose clients address a comment by a stable integer returns number as that id and reads it back with getCommentByNumber(number) — never hand-build an id from the UUID. createNumberedComment() is this same create under the name that path reads best; numberComment(id) numbers a row that was inserted without this function.

Both __setup__ SQL files are required (comments, comment_numbers).

function createComment(
  resourceType: string,
  resourceId: string,
  userId: string | null,
  data: CreateCommentInput,
): Promise<NumberedComment>
  • resourceType — The type of resource being commented on.
  • resourceId — The ID of the resource being commented on.
  • userId — The ID of the commenting user.
  • data — The comment creation input.

Returns: The created comment with its sequential number.

getCommentsByResource(resourceType, resourceId, options)

Retrieves paginated comments for a resource, ordered by creation date descending. Only returns top-level comments (no replies).

The rows carry each comment's UUID id and its stable number when numbered. An integer-addressed API returns that number as its external id, never the page index. A raw import may have no number; call numberComment(id) explicitly before exposing it through an integer-addressed API.

function getCommentsByResource(
  resourceType: string,
  resourceId: string,
  options?: PaginationOptions,
): Promise<PaginatedResult<Comment>>
  • resourceType — The type of resource.
  • resourceId — The ID of the resource.
  • options — Pagination options.

Returns: A paginated result of comments.

getCommentById(commentId)

Retrieves a single comment by ID.

function getCommentById(commentId: string): Promise<Comment | null>
  • commentId — The comment's UUID. For the sequential integer an integer-addressed API uses, call getCommentByNumber(number) instead.

Returns: The comment or null if not found.

updateComment(commentId, userId, data)

Updates a comment. Only the comment owner can update.

function updateComment(
  commentId: string,
  userId: string,
  data: UpdateCommentInput,
): Promise<Comment | null>
  • commentId — The comment's UUID. For an integer number, resolve it with getCommentByNumber(number) first.
  • userId — The requesting user's ID (must match comment owner).
  • data — The update input.

Returns: The updated comment or null if not found or unauthorized.

deleteComment(commentId, userId)

Deletes a comment. Allowed for the comment owner, or for a parent-resource moderator permitted by a registered resource access policy (action: 'moderate'), which lets resource owners remove guest or unwanted comments on their own content.

function deleteComment(commentId: string, userId: string): Promise<boolean>
  • commentId — The comment's UUID. To delete by the integer number an API exposes, look the row up with getCommentByNumber(number) and pass its id.
  • userId — The requesting user's ID (comment owner or parent-resource moderator).

Returns: true if deleted, false if not found or unauthorized.

getReplies(commentId, options)

Retrieves paginated replies to a comment, ordered by creation date ascending, with each reply's stable number when numbered, like getCommentsByResource.

function getReplies(
  commentId: string,
  options?: PaginationOptions,
): Promise<PaginatedResult<Comment>>
  • commentId — The parent comment ID.
  • options — Pagination options.

Returns: A paginated result of reply comments.

getCommentCount(resourceType, resourceId)

Returns the total number of comments on a resource (including replies).

function getCommentCount(resourceType: string, resourceId: string): Promise<number>
  • resourceType — The type of resource.
  • resourceId — The ID of the resource.

Returns: The total comment count.

Constants

requestHandlerMap

Handler map for comment routes.

const requestHandlerMap: {
  readonly rateLimitComments: MoleculeRequestHandler
  readonly create: typeof create
  readonly list: typeof list
  readonly commentCount: typeof commentCount
  readonly read: typeof read
  readonly update: typeof update
  readonly del: typeof del
  readonly replies: typeof replies
}

routes

Routes for comment CRUD and threaded replies.

const routes: readonly [
  {
    readonly method: 'post'
    readonly path: '/:resourceType/:resourceId/comments'
    readonly handler: 'create'
    readonly middlewares: readonly ['authenticate', 'rateLimitComments']
  },
  {
    readonly method: 'get'
    readonly path: '/:resourceType/:resourceId/comments'
    readonly handler: 'list'
  },
  {
    readonly method: 'get'
    readonly path: '/:resourceType/:resourceId/comments/count'
    readonly handler: 'commentCount'
  },
  { readonly method: 'get'; readonly path: '/comments/:commentId'; readonly handler: 'read' },
  {
    readonly method: 'put'
    readonly path: '/comments/:commentId'
    readonly handler: 'update'
    readonly middlewares: readonly ['authenticate']
  },
  {
    readonly method: 'delete'
    readonly path: '/comments/:commentId'
    readonly handler: 'del'
    readonly middlewares: readonly ['authenticate']
  },
  {
    readonly method: 'get'
    readonly path: '/comments/:commentId/replies'
    readonly handler: 'replies'
  },
]

createCommentSchema

Schema for validating comment creation input.

const createCommentSchema: z.ZodObject<
  {
    body: z.ZodString
    parentId: z.ZodOptional<z.ZodString>
    authorName: z.ZodOptional<z.ZodString>
  },
  z.core.$strip
>

updateCommentSchema

Schema for validating comment update input.

const updateCommentSchema: z.ZodObject<{ body: z.ZodString }, z.core.$strip>

Injection Notes

Requirements

Peer dependencies:

  • @molecule/api-database ^1.1.0
  • @molecule/api-i18n ^1.0.1
  • @molecule/api-logger ^1.0.1
  • @molecule/api-rate-limit ^1.0.1
  • @molecule/api-resource ^1.5.0
  • express ^5.0.0
  • zod ^4.0.0

Runtime Dependencies

  • @molecule/api-database

  • @molecule/api-i18n

  • @molecule/api-logger

  • @molecule/api-rate-limit

  • @molecule/api-resource

  • express

  • zod

  • List endpoints return a PAGINATED envelope { data, total, limit, offset }, not a bare array — read the rows off result.data (server). On the client, unwrapList(res) from @molecule/app-http normalizes this envelope (pass it the whole HttpResponse), so the rows come back; reading the response as a bare array — or res.data alone (which is the envelope) — yields an EMPTY list.

  • A scaffold that lists this package already has these tables — its __setup__ SQL is copied into the app at create time and replayed on every boot, so do not copy it into api/migrations/ yourself; only a package added after the scaffold needs that. Both SQL files this package ships — src/__setup__/comments.sql and src/__setup__/comment_numbers.sql — must exist in the target database before use (scaffolded apps apply both automatically; existing apps must apply both first).

  • Integer comment ids — every comment is numbered by default. createComment() writes the comment and its sequential number (1, 2, 3, …) together and returns both; createNumberedComment() is the same create under the name an integer-id API reads best. Paginated comments and replies also carry that stable number. Never derive an identity from the page index: sorting, pagination and deletion change positions. For an API whose clients address a comment by a stable integer, return number as the id and read it back with getCommentByNumber(n) — never hand-build an id from the UUID, and never read a missing commentNumbers(ids) entry as 0 (a row inserted without createComment() has no number; numberComment(id) gives it one). Never build your own id-mapping table.

  • Parent-resource visibility and publication policies. list, read, replies, count, and create enforce any policy registered via registerResourceAccessPolicy(resourceType, check) (or '*' as a fallback). When denied, handlers return 404 and createComment runs the access check and insert atomically inside a database transaction (when supported by the bonded pool) to prevent check-then-write races. Sibling resources such as @molecule/api-resource-article register their visibility rules automatically on import (rejecting comments on unpublished drafts and hiding draft comments from non-authors). For your own private resources, call registerResourceAccessPolicy('my-type', ({ resourceId, action, viewerId }) => …) at startup. When no policy is registered for a type, reads remain public.

  • The author is always the session user. Create/update/delete require authenticate; the create handler ignores any client-supplied author id, and update/delete verify ownership in the handler — keep those properties in any custom path.

  • The parent is polymorphic and unverified (no FK on resourceType/resourceId): validate that the target exists in your domain code if orphaned threads matter, and reuse the same canonical type slugs as your other polymorphic resources (bookmarks, activity feed).

  • Clean up threads when an account or its articles are deleted. After the parent and comment tables exist, copy sql/<dialect>/user.sql and, for apps with articles, sql/<dialect>/article.sql from this package into new numbered app migrations. Use sqlite for SQLite or D1, postgresql for PostgreSQL 14+ or PGlite, and mysql for MySQL 8.4. On MySQL, also copy sql/mysql/user-article-cascade.sql only when articles.authorId references users.id ON DELETE CASCADE. Apply these files with the app's migration runner before serving traffic (wrangler d1 migrations apply on D1). The triggers remove threads for the deleted parent, including replies and numbers, in the same transaction. The user hook also clears any surviving comment's reference to its deleted author. Each file assumes resourceId stores the parent's ID and resourceType is user / users or article / articles. For a custom type, table or parent key (such as an article slug), adapt the predicate to the values your app stores before applying the migration.

  • Client: address the thread with an identifier the page already has, not with the loaded parent. List and post with /:resourceType/:resourceId/comments, using the parent identifier from the route when it is the one this API expects; when the route carries something else (a slug where the API needs an id), resolve the id first and keep the comment controls visibly disabled until it is known. Edit and delete a comment by its own id (PUT/DELETE /comments/:commentId). A submit handler that starts with if (!parent) return does nothing when the user submits before the parent finishes loading: no request, no error, the text still in the box. Never let a click silently do nothing.

E2E Tests

Integration checklist — drive the real UI (live preview, no mocks), adapt each item to this app's actual screens/flows, and check every box off one by one. A box you can't check is an integration bug to fix — not a skip:

  • Posting a comment on a commentable resource shows it in the thread immediately and it persists across a full reload.
  • Replying to a comment renders the reply nested under its parent.
  • The author can edit their own comment and the updated text persists; a DIFFERENT signed-in user gets no edit/delete controls on it and a direct attempt is denied.
  • Deleting an own comment removes it per the app's policy (gone or tombstone) and stays removed after reload.
  • A long thread paginates ("load more" fetches older comments) without duplicating or dropping entries.
  • A resource with no comments shows a readable empty state.