Comments Plugin Pattern
Attach comments to any resource with a definePlugin plugin that owns its table and follows the host's deletes.
This recipe is the comments plugin from examples/extensions. One use() call gives a resource comments with CRUD routes of their own. The plugin owns its table, checks its options, deletes a record's comments when the record is deleted, declares a comments.added event and ships a dashboard page.
Plugin implementation
import {
ActionExecutionError,
definePlugin,
emitEvent,
eq,
t,
} from "@brickkit/core";
import { crud } from "@brickkit/crud";
export const comments = definePlugin({
name: "@brick-examples/comments",
brick: "^0.11.0",
requires: ["@brickkit/crud"],
options: t.Object({
maxLength: t.Integer({
default: 2000,
minimum: 1,
description: "The longest comment body, in characters.",
}),
}),
// Built for the host database's engine, named <resource>_comments.
tables: ({ table, text, timestamp }) => ({
comments: table("comments", {
id: text("id")
.primaryKey()
.$defaultFn(() => crypto.randomUUID()),
targetId: text("target_id").notNull(),
body: text("body").notNull(),
createdAt: timestamp("created_at")
.notNull()
.$defaultFn(() => new Date()),
}),
}),
events: { added: t.Object({ id: t.String(), targetId: t.String() }) },
resource: ({ resource, service, tables, options, events, hooks }) => {
const table = tables.comments;
const clean = (body: unknown) => {
const text = String(body ?? "").trim();
if (!text)
throw new ActionExecutionError(
"BAD_REQUEST",
"Comment body cannot be blank",
400,
);
if (text.length > options.maxLength)
throw new ActionExecutionError(
"BAD_REQUEST",
`Comment body is longer than ${options.maxLength} characters`,
400,
);
return text;
};
// A deleted record takes its comments along, in the same transaction.
hooks.afterDelete(({ id, tx }) =>
tx.delete(table).where(eq(table.targetId, String(id))),
);
const comment = service
.resource({ name: `${resource.name}Comment`, table, id: table.id })
.use(
crud({
access: "public",
fields: {
id: { read: true, filter: ["eq"] },
targetId: { read: true, create: true, filter: ["eq"] },
body: {
read: true,
create: true,
update: true,
filter: ["contains"],
},
createdAt: { read: true, sort: true },
},
hooks: {
beforeCreate: async ({ data, tx }) => {
data.body = clean(data.body);
const parents = await tx
.select({ id: resource.id })
.from(resource.table)
.where(eq(resource.id, data.targetId))
.limit(1);
if (!parents.length)
throw new ActionExecutionError(
"NOT_FOUND",
"Comment target not found",
404,
);
},
beforeUpdate: ({ data }) => {
if (data.body !== undefined) data.body = clean(data.body);
},
// Recorded only when the app records events (brick({ events })).
afterCreate: async ({ row, ctx, tx }) => {
if (service.recorder)
await emitEvent(
ctx,
events.added,
{ id: String(row.id), targetId: String(row.targetId) },
{ tx },
);
},
},
}),
);
return { comments: comment };
},
dashboard: "./dashboard.tsx",
});Installing it
import {
defineDatabase,
defineService,
sqliteTable,
syncSchema,
text,
} from "@brickkit/core";
import { crud } from "@brickkit/crud";
import { comments } from "../plugins/comments";
export const pagesTable = sqliteTable("pages", {
id: text("id").primaryKey(),
title: text("title").notNull(),
});
const database = defineDatabase({ tables: { pages: pagesTable } });
export const pagesService = defineService("pages", { database });
export const page = pagesService
.resource({ name: "page", table: pagesTable, id: pagesTable.id })
.use(
crud({
access: "public",
fields: { id: { read: true }, title: { read: true, create: true } },
}),
)
.use(comments({ maxLength: 500 }));
// Development: creates pages and the plugin's page_comments.
syncSchema(pagesService);The app does not import or declare the comments table: the plugin adds page_comments to the database, where syncSchema and migrations find it. Installing on a second resource (post.use(comments())) gives that resource its own post_comments.
Schema
Table Name: page_comments
| Field | Type | Description |
|---|---|---|
id | text | Row identifier. PK Default: crypto.randomUUID() (application) |
target_id | text | The commented record's id, checked to exist on create. |
body | text | Trimmed text, at most maxLength characters. |
created_at | integer (SQLite) / timestamptz (Postgres) | When the comment was written. Default: new Date() (application) |
Routes
The comment resource gets the standard CRUD routes under its service, with the resource name in kebab-case (pageComment → page-comment, see URL Scheme):
POST /api/pages/page-comment(create)POST /api/pages/page-comment/query(list)POST /api/pages/page-comment/countandPOST /api/pages/page-comment/existsGET,PATCHandDELETE /api/pages/page-comment/:id
The typed client reaches them as api.pages.pageComment.list() and so on; in process, page.comments.list(...). OpenAPI and the dashboard label them with @brick-examples/comments.
The recipe allows anyone to edit or delete any comment. For per-author comments, add an owner column and return an ownership scope from an access policy, or make access one of the plugin's options.