@molecule/api-resource-comment

API resource · comments · API (Node) · v1.1.4 · 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

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 numbered comment, 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-resource zod

API

Interfaces

Comment

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

interface Comment {
  /** Unique comment identifier. */
  id: string
  /** 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. */
  userId: string
  /** 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
}

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
}

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

NumberedComment

A comment together with its sequential number.

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

Functions

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.

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.

function createNumberedComment(
  resourceType: string,
  resourceId: string,
  userId: string,
  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.

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. Comments without a number are left out of the map.

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.

function createComment(
  resourceType: string,
  resourceId: string,
  userId: string,
  data: CreateCommentInput,
): Promise<Comment>
  • 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.

getCommentsByResource(resourceType, resourceId, options)

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

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 ID to look up.

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 ID to update.
  • 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. Only the comment owner can delete.

function deleteComment(commentId: string, userId: string): Promise<boolean>
  • commentId — The comment ID to delete.
  • userId — The requesting user's ID (must match comment owner).

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

getReplies(commentId, options)

Retrieves paginated replies to a comment, ordered by creation date ascending.

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 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']
  },
  {
    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> },
  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-resource ^1.0.1
  • zod ^4.0.0

Runtime Dependencies

  • @molecule/api-database

  • @molecule/api-i18n

  • @molecule/api-logger

  • @molecule/api-resource

  • 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. src/__setup__/comments.sql ships with this package and must exist in the target database before use (scaffolded apps apply it automatically; existing apps must apply it first).

  • Integer comment ids (RealWorld's comment.id, most public API specs): keep the UUID and give each comment a sequential number — createNumberedComment() creates both in one transaction, getCommentByNumber(n) finds it, commentNumbers(ids) maps a list. Apply src/__setup__/comment_numbers.sql too. Never build your own id-mapping table.

  • Reads are PUBLIC by default. list, read, replies, and count ship with no auth middleware (comment threads on public content). If the commented resources are private in your app, add an authorizer that checks access to the PARENT resource before serving its comments.

  • 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).

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.