@molecule/api-resource-article
API resource · articles · API (Node) · v1.9.1 · Apache-2.0
Articles and blog posts: unique slugs, draft/publish workflow, search, tags, favorites, a followed-authors feed, and filtered, paginated lists
npm install @molecule/api-resource-articleHow it works
@molecule/api-resource-article is an API resource: the routes, validation and storage for articles, built on the database and auth cores so it runs on whichever providers your app has bonded.
import { routes, requestHandlerMap } from '@molecule/api-resource-article'
// Wire routes into your Express app via mlcl inject:
// POST /articles create (signed in; optional status: 'draft' | 'published', default 'published')
// GET /articles ?tag= &authorId= &favoritedBy= &status=published|draft|all &q= &limit= &offset=
// GET /articles/feed authors the signed-in user follows
// GET /articles/tags every tag in use, most-used first (?limit= caps it)
// GET /articles/:slug
// PUT /articles/:slug author only; a new title gives a new slug
// DELETE /articles/:slug author only
// POST /articles/:slug/favorite idempotent
// DELETE /articles/:slug/favorite idempotentWorks with: @molecule/api-database, @molecule/api-i18n, @molecule/api-logger, @molecule/api-resource, @molecule/api-slug
Reference
Articles and blog posts for molecule.dev.
Articles with unique slugs, draft/publish status (status: 'draft' | 'published',
publishedAt), case-insensitive search (?q=), tags, favorites, a feed of the
authors a user follows, and lists filtered by status, search query, tag, author and
who favorited them — the domain of a blog, a Medium-style platform (RealWorld
"Conduit"), a news or docs site. Favorites are @molecule/api-resource-reaction
reactions and the feed reads @molecule/api-resource-follow's follows, so they are
the same favorites and follows the rest of the app sees.
Tables this package owns: articles and article_tags. The join between them is
article_tags.articleId = articles.id (a declared FK, ON DELETE CASCADE; ("articleId", "tag") is
unique, and article_tags.position is the order the tags were given in). Optional favorites and
followed-author feeds integrate with @molecule/api-resource-reaction and
@molecule/api-resource-follow when those packages are installed; without them, articles run
standalone with zero unused tables or routes.
Edit the scaffold's Express routes in api/src/handlers/articles.ts. Adjust paths,
request fields and JSON there. Use createArticle, updateArticle, deleteArticle,
setFavorite and the read services for validation, ownership and storage.
Apps using the package's own handler map can call createArticleHandlers({ mapRequest, mapResponse }).
mapRequest can unwrap bodies and resolve query filters. For a list, put resolved user
ids in query.authorId and query.favoritedBy, the same names used by listArticles.
Async mapResponse can batch-load author profiles, omit fields from list items,
rename pagination keys, wrap results, or translate error statuses and bodies. It receives errors
and empty deletes too. Set the authenticated user on res.locals.session.userId.
For profile projection, pass the page's authorIds once to
getPublicProfiles(ids) from @molecule/api-resource-user and
getFollowedIds(viewerId, 'user', ids) from @molecule/api-resource-follow.
Join those maps while projecting the page. This keeps the page at two relationship
queries even when many entries share an author; per-entry lookups repeat the same work.
import {
createArticleHandlers,
listArticles,
type ListArticlesOptions,
} from '@molecule/api-resource-article'
export const requestHandlerMap = createArticleHandlers({
mapRequest: (req) => ({ body: req.body?.entry }),
mapResponse: (result) =>
result.statusCode >= 400 || result.statusCode === 204
? result
: { ...result, body: { entry: result.body } },
})
// For a custom list route, resolve public handles to user ids in the app.
// Pass those ids as authorId and favoritedBy, and the current reader as viewerId.
export async function listEntryPreviews(filters: ListArticlesOptions) {
const { data, total } = await listArticles(filters)
return {
entries: data.map(({ id, slug, title, favorited }) => ({ id, slug, title, favorited })),
entriesCount: total,
}
}
Use the resulting map's handlers on the app's routes. For distinct route projections,
create separate maps with separate options. The static requestHandlerMap keeps the
native flat-body/raw-article format. A list can combine tag, author and favorites
filters with limit and offset. The list reads author as a legacy alias when
authorId is absent or blank. If a requested handle cannot be resolved, return
{ response: { statusCode: 200, body: { data: [], total: 0, limit, offset } } }
from mapRequest to let mapResponse project the empty page.
getFeed(viewerId, { limit, offset }) handles the followed-author view.
The services read the package's tables, so a differently named table with its own
schema needs its own persistence.
Need only a lookup in a custom route? findArticleRow(slug) returns the stored
ArticleRow or null. getArticleBySlug(slug, viewerId?) returns an Article or
null, with ordered tags, favorite count and the viewer's favorited state.
Both read this package's articles table. Keep your route, author-profile lookup
and response projection local; call these functions instead of copying the slug query.
uniqueArticleSlug(title, excludeId?) exposes the same free-slug policy used by
createArticle and updateArticle, including reserved route words and the
article fallback. Use it for a custom workflow that needs a slug before writing;
use createArticle for a normal create. It checks availability without reserving
a slug, so retain the UNIQUE index and retry a conflicting insert. A different
table can use uniqueSlugInTable(table, column, title, { excludeId }) from
@molecule/api-slug; its general policy does not reserve this resource's routes.
import { findArticleRow } from '@molecule/api-resource-article'
const slug = 'release-notes'
const row = await findArticleRow(slug)
// Map row (or null) into this API's response. Use getArticleBySlug for hydrated fields.
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.tsJSDoc, not this file.
Quick Start
import { routes, requestHandlerMap } from '@molecule/api-resource-article'
// Wire routes into your Express app via mlcl inject:
// POST /articles create (signed in; optional status: 'draft' | 'published', default 'published')
// GET /articles ?tag= &authorId= &favoritedBy= &status=published|draft|all &q= &limit= &offset=
// GET /articles/feed authors the signed-in user follows
// GET /articles/tags every tag in use, most-used first (?limit= caps it)
// GET /articles/:slug
// PUT /articles/:slug author only; a new title gives a new slug
// DELETE /articles/:slug author only
// POST /articles/:slug/favorite idempotent
// DELETE /articles/:slug/favorite idempotent
// Configure a publishing API's envelopes without rewriting its operations:
import { createArticleHandlers } from '@molecule/api-resource-article'
const publishing = createArticleHandlers({
mapRequest: (req) => ({ body: req.body?.entry }),
mapResponse: async (result) => {
// Preserve validation, authorization, missing rows and empty deletes.
if (result.statusCode >= 400 || result.statusCode === 204) return result
// The app owns its projection. A list can batch-load author profiles here.
return { ...result, body: { entry: result.body } }
},
})
router.post('/entries', publishing.create) // authenticated session remains required
router.get('/entries/:slug', publishing.read)
// mapRequest can also resolve an external filter name to a user id in req.query.
// If a lookup finds nothing, return { response: { statusCode, body } } with
// this API's empty-page response before querying. Never drop the filter.
// Keep extra domain validation in route middleware before these handlers.
// For a different domain model or custom workflow, call createArticle/listArticles
// from a local route instead. The default requestHandlerMap never adopts these mappings.
// RealWorld's `GET /api/tags` returns EVERY tag in use — that is `allTags()`,
// not `popularTags()`, whose default is the top 20:
import { allTags } from '@molecule/api-resource-article'
router.get('/api/tags', async (_req, res) => {
res.json({ tags: (await allTags()).map((tag) => tag.tag) })
})
Type
resource
Installation
npm install @molecule/api-resource-article @molecule/api-database @molecule/api-i18n @molecule/api-logger @molecule/api-resource @molecule/api-slug express zod
npm install -D @types/express
API
Interfaces
ArticleRow
An article row as stored. tagList is a JSON array of tag names, in the order they were
given, and it is what every article response returns. The article_tags table holds the same
tags one row each, for the tag filter and the tag lists. createArticle and updateArticle
write both, so an app that goes through this package never keeps them in step itself.
interface ArticleRow {
/** Unique article identifier. */
id: string
/** URL slug, unique across articles. */
slug: string
/** Title. */
title: string
/** Short summary shown in lists. */
description: string
/** Full body (markdown or plain text — the app decides how to render it). */
body: string
/** Tag names, JSON-encoded. */
tagList: string
/** The user who wrote it. */
authorId: string
/** Publication state (`'published'` by default on legacy rows). */
status?: ArticleStatus
/** When it was published (ISO 8601), or `null` for drafts. */
publishedAt?: string | null
/** Optional custom JSON metadata (e.g. `{ coverImageUrl }` or domain fields). */
metadata?: string
/** When it was created (ISO 8601, millisecond precision). */
createdAt: string
/** When it was last updated (ISO 8601). */
updatedAt: string
}
ArticleAuthor
Public display profile attached to an article when @molecule/api-resource-user is loaded.
interface ArticleAuthor {
/** 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
}
Article
An article as the service returns it: tags decoded, favorites counted, and whether the viewing user favorited it.
interface Article {
/** Unique article identifier. */
id: string
/** URL slug, unique across articles. */
slug: string
/** Title. */
title: string
/** Short summary shown in lists. */
description: string
/** Full body. */
body: string
/** Tag names, in the order they were given. */
tagList: string[]
/** The user who wrote it. */
authorId: string
/** Hydrated public author profile when `@molecule/api-resource-user` is loaded. */
author?: ArticleAuthor | null
/** Publication state (`'draft'` or `'published'`). */
status: ArticleStatus
/** When it was published (ISO 8601), or `null` while in draft. */
publishedAt: string | null
/** Optional custom JSON metadata when set (e.g. `{ coverImageUrl }`). */
metadata?: Record<string, unknown>
/** When it was created (ISO 8601). */
createdAt: string
/** When it was last updated (ISO 8601). */
updatedAt: string
/** How many users favorited it. */
favoritesCount: number
/** Whether the viewing user favorited it (`false` with no viewer). */
favorited: boolean
}
CreateArticleInput
Input for creating an article.
interface CreateArticleInput {
/** Title (the slug is derived from it). */
title: string
/** Short summary. */
description?: string
/** Full body. */
body: string
/** Tag names. */
tagList?: string[]
/** Publication state (`'published'` when omitted). */
status?: ArticleStatus
/** Optional custom JSON metadata (e.g. `{ coverImageUrl }`, max 16 KB serialized). */
metadata?: Record<string, unknown>
}
UpdateArticleInput
Input for updating an article. A changed title gives the article a new slug
unless preserveSlug: true is passed to keep existing public permalinks stable.
interface UpdateArticleInput {
/** New title. */
title?: string
/** New summary. */
description?: string
/** New body. */
body?: string
/** New tag names (replaces the old ones). */
tagList?: string[]
/** New publication state (`'draft'` or `'published'`). */
status?: ArticleStatus
/** When `true`, keep the current `slug` even if `title` changes. */
preserveSlug?: boolean
/** Optional custom JSON metadata replacement (max 16 KB serialized). */
metadata?: Record<string, unknown>
}
ListArticlesOptions
Filters and paging for listArticles.
interface ListArticlesOptions {
/** Only articles with this tag. */
tag?: string
/** Only articles by this author id. */
authorId?: string
/** Only articles this user id favorited. */
favoritedBy?: string
/**
* Publication state filter (default `'published'`).
* `'draft'` and `'all'` only expose drafts belonging to `viewerId`.
*/
status?: ArticleStatusFilter
/** Case-insensitive search query across title, description, body, and tags. */
q?: string
/** Page size (default 20, at most 100). */
limit?: number
/** Rows to skip. */
offset?: number
/** The viewing user, for `favorited` and viewing own drafts; null or omitted means an anonymous reader. */
viewerId?: string | null
}
PaginatedArticles
A page of articles.
interface PaginatedArticles {
/** The articles on this page, newest first. */
data: Article[]
/** Articles matching the filters across all pages. */
total: number
/** Page size used. */
limit: number
/** Rows skipped. */
offset: number
}
TagCount
A tag and how many articles carry it.
interface TagCount {
/** Tag name. */
tag: string
/** Articles with this tag. */
count: number
}
Types
ArticleRequestHandlerMap
HTTP handlers for all article routes. Authorization stays in each operation.
type ArticleRequestHandlerMap = {
[Name in keyof typeof operations]: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
}
AuthorChange
The outcome of a change that only the author may make.
type AuthorChange<T> =
{ status: 'ok'; article: T } | { status: 'not_found' } | { status: 'forbidden' }
ArticleStatus
Publication state of an article.
'published'(default): visible to all readers and listed in public feeds and tags.'draft': visible only to its author until published.
type ArticleStatus = 'draft' | 'published'
ArticleStatusFilter
Filter for article publication state in ListArticlesOptions.
'all' returns drafts and published articles for the signed-in author only.
type ArticleStatusFilter = ArticleStatus | 'all'
Functions
createArticleHandlers(options)
Create article handlers for this project's wire format. Adapt an envelope, filter names or response projection without rewriting the article operations. Each mapping receives the adapted request and its original response context. Omit the options for the standard flat-body, raw-article and paginated-list API. Error and partial responses reach mapResponse too, so preserve them explicitly.
function createArticleHandlers(options?: RequestHandlerOptions): ArticleRequestHandlerMap
options— Shared resource request/response mappings, scoped to this map.
Returns: A route-compatible map with the same names as requestHandlerMap.
uniqueArticleSlug(title, excludeId)
Find a free slug in this package's articles table without writing an article. Uses the same normalization, reserved route slugs and fallback as createArticle and updateArticle. This is a lookup, not a reservation: keep the table's UNIQUE index and retry a conflicting insert. For another table use api-slug's uniqueSlugInTable instead.
function uniqueArticleSlug(title: string, excludeId?: string): Promise<string>
title— The article title.excludeId— The existing article's id, so it may keep its own slug on update.
Returns: An unused article slug; empty normalized titles use article.
hydrateArticles(rows, viewerId)
Turn stored rows into Articles: decoded tags, favorite counts and the
viewer's own favorites, in two queries for the whole page.
function hydrateArticles(rows: ArticleRow[], viewerId?: string | null): Promise<Article[]>
rows— Article rows.viewerId— The viewing user, if any; null and undefined are anonymous.
Returns: The articles, in the order given.
createArticle(authorId, input)
Create an article with a unique slug derived from its title.
createdAt and updatedAt are stamped by this call and strictly increase
within the process, so two articles created in the same millisecond still
list newest first — callers never write these columns.
function createArticle(authorId: string, input: CreateArticleInput): Promise<Article>
authorId— The writing user.input— Title, body, optional description and tags.
Returns: The created article.
findArticleRow(slug)
The stored row for a slug.
function findArticleRow(slug: string): Promise<ArticleRow | null>
slug— The article slug.
Returns: The row, or null.
getArticleBySlug(slug, viewerId)
An article by slug. Drafts are visible only to their author (viewerId === row.authorId);
any other viewer receives null.
function getArticleBySlug(slug: string, viewerId?: string | null): Promise<Article | null>
slug— The article slug.viewerId— The viewing user, forfavoritedand draft visibility; null or omitted is anonymous.
Returns: The article, or null.
getArticleById(id, viewerId)
An article by immutable ID. Drafts are visible only to their author
(viewerId === row.authorId); any other viewer receives null.
function getArticleById(id: string, viewerId?: string | null): Promise<Article | null>
id— The article UUID.viewerId— The viewing user, forfavoritedand draft visibility; null or omitted is anonymous.
Returns: The article, or null.
listArticles(options)
Articles newest first, filtered by status, search query, tag, author and who favorited them.
Defaults to 'published' articles only; 'draft' and 'all' only include drafts belonging to viewerId.
function listArticles(options?: ListArticlesOptions): Promise<PaginatedArticles>
options— Filters, paging and the viewer.
Returns: A page of articles and the total matching.
getFeed(userId, options)
Articles by the users userId follows, newest first.
Reads the reader's follows rows where targetType is 'user' and matches
each row's targetId against articles.authorId, so the two sides must use
the SAME user identity: targetId is the target user's id — the value
createArticle stored in article.authorId — never a username or display
handle. A route or handler that receives a username resolves it to that id
before calling follow; @molecule/api-resource-follow stores the identifier
it is given unchanged, so a username-keyed follow contributes no articles.
function getFeed(
userId: string,
options?: { limit?: number; offset?: number },
): Promise<PaginatedArticles>
userId— The reader.options— Paging.
Returns: A page of articles and the total.
updateArticle(slug, userId, input)
Update an article. Only its author may; a changed title gives it a new slug.
updatedAt always moves strictly past the stored value — even an edit in the
same millisecond as the create shows a changed updatedAt — so callers never
set it themselves.
function updateArticle(
slug: string,
userId: string,
input: UpdateArticleInput,
): Promise<AuthorChange<Article>>
slug— The article slug.userId— The requesting user.input— The fields to change.
Returns: The updated article, or why not.
deleteArticle(slug, userId)
Delete an article and its tags and favorites. Only its author may.
function deleteArticle(slug: string, userId: string): Promise<AuthorChange<true>>
slug— The article slug.userId— The requesting user.
Returns: Whether it was deleted, or why not.
setFavorite(slug, userId, favorite)
Favorite or unfavorite an article for a user (idempotent both ways).
function setFavorite(slug: string, userId: string, favorite: boolean): Promise<Article | null>
slug— The article slug.userId— The user.favorite— True to favorite, false to remove the favorite.
Returns: The article after the change, or null when there is no such article.
allTags()
Every tag in use, most-used first (ties alphabetical).
This is the list a GET /tags endpoint returns, in the shape RealWorld's
GET /api/tags asks for: all of the tags in use, however many the
database holds. Use it for that endpoint — popularTags is the top-N
leaderboard and its default of 20 silently drops every tag past the
twentieth.
function allTags(): Promise<TagCount[]>
Returns: Every tag in use, with its article count.
popularTags(limit)
The limit most-used tags, most-used first (ties alphabetical).
This is a leaderboard, not "every tag". The default is the top 20, so a
GET /tags-shaped endpoint that returns all tags in use (RealWorld's
GET /api/tags) must call allTags — or pass
Number.POSITIVE_INFINITY — or it silently drops every tag past the
twentieth once the database holds more than 20. Pass an explicit limit
when the caller really did ask for the N most-used, e.g. a sidebar of ten.
function popularTags(limit?: number): Promise<TagCount[]>
limit— How many tags to return, most-used first (default 20;Number.POSITIVE_INFINITYfor every tag).
Returns: The tags with their article counts.
checkArticleResourceAccess(context)
Parent-resource access policy for polymorphic attachments (such as
@molecule/api-resource-comment) targeting an article by ID or slug.
- Missing articles are never accessible (
false). 'create'(e.g. posting a comment) is permitted only on published articles.'moderate'(e.g. deleting guest or unwanted comments) is permitted only for the article's author.'read'is permitted on published articles for any viewer, and on drafts only for their author.
function checkArticleResourceAccess(context: {
resourceType?: string
resourceId: string
action: 'read' | 'create' | 'moderate'
viewerId?: string | null
}): Promise<boolean>
context— Resource access request context.context.resourceId— Article UUID or slug.context.action—'read','create', or'moderate'.context.viewerId— Signed-in viewer ID, ornull/undefinedfor anonymous callers.
Returns: true when the viewer may perform action on the article's attachments.
registerArticleResourceAccess(force)
Registers checkArticleResourceAccess under 'article' and 'articles' in
the shared process-wide resource access policy registry read by polymorphic resource
packages such as @molecule/api-resource-comment. Existing custom policies are kept
unless force is true.
function registerArticleResourceAccess(force?: boolean): void
force— Whentrue, replaces any existing policy registered for'article'/'articles'.
Constants
create
Create an article from a flat body as the session user.
const create: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
list
List articles with the standard filters and pagination envelope.
const list: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
feed
List articles by followed authors for the session user.
const feed: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
tags
Return tags in use, optionally capped by the requested limit.
const tags: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
read
Read an article by slug, including the viewer's favorite state.
const read: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
update
Update an article as its author.
const update: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
del
Delete an article as its author, returning an empty 204.
const del: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
favorite
Favorite an article as the session user.
const favorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
unfavorite
Unfavorite an article as the session user.
const unfavorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
requestHandlerMap
Handler map for article routes.
const requestHandlerMap: {
readonly create: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
readonly list: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
readonly feed: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
readonly tags: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
readonly read: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
readonly update: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
readonly del: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
readonly favorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
readonly unfavorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>
}
routes
Routes for articles, the feed, tags and favorites.
const routes: readonly [
{
readonly method: 'post'
readonly path: '/articles'
readonly handler: 'create'
readonly middlewares: readonly ['authenticate']
},
{ readonly method: 'get'; readonly path: '/articles'; readonly handler: 'list' },
{
readonly method: 'get'
readonly path: '/articles/feed'
readonly handler: 'feed'
readonly middlewares: readonly ['authenticate']
readonly optional: 'follows'
},
{ readonly method: 'get'; readonly path: '/articles/tags'; readonly handler: 'tags' },
{ readonly method: 'get'; readonly path: '/articles/:slug'; readonly handler: 'read' },
{
readonly method: 'put'
readonly path: '/articles/:slug'
readonly handler: 'update'
readonly middlewares: readonly ['authenticate']
},
{
readonly method: 'delete'
readonly path: '/articles/:slug'
readonly handler: 'del'
readonly middlewares: readonly ['authenticate']
},
{
readonly method: 'post'
readonly path: '/articles/:slug/favorite'
readonly handler: 'favorite'
readonly middlewares: readonly ['authenticate']
readonly optional: 'reactions'
},
{
readonly method: 'delete'
readonly path: '/articles/:slug/favorite'
readonly handler: 'unfavorite'
readonly middlewares: readonly ['authenticate']
readonly optional: 'reactions'
},
]
ARTICLE_RESOURCE_TYPE
The resource type favorites and comments on articles are stored under.
const ARTICLE_RESOURCE_TYPE: 'article'
FAVORITE_REACTION
The reaction type a favorite is stored as.
const FAVORITE_REACTION: 'favorite'
RESERVED_ARTICLE_SLUGS
Slugs the routes use for themselves (/articles/feed, /articles/tags): an
article titled "Feed" gets feed-2, or its page would be unreachable.
const RESERVED_ARTICLE_SLUGS: ReadonlySet<string>
MAX_ARTICLES_PAGE
Largest page a list returns.
const MAX_ARTICLES_PAGE: 100
articleStatusSchema
Publication state for creating or updating an article.
const articleStatusSchema: z.ZodEnum<{ draft: 'draft'; published: 'published' }>
articleStatusFilterSchema
Publication state filter for listing articles.
const articleStatusFilterSchema: z.ZodEnum<{ draft: 'draft'; published: 'published'; all: 'all' }>
articleMetadataSchema
Optional custom JSON metadata object (e.g. { coverImageUrl }), bounded to 16 KB serialized.
const articleMetadataSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>
createArticleSchema
Schema for creating an article.
const createArticleSchema: z.ZodObject<
{
title: z.ZodString
description: z.ZodOptional<z.ZodString>
body: z.ZodString
tagList: z.ZodOptional<z.ZodArray<z.ZodString>>
status: z.ZodOptional<z.ZodEnum<{ draft: 'draft'; published: 'published' }>>
metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>
},
z.core.$strip
>
updateArticleSchema
Schema for updating an article (every field optional).
const updateArticleSchema: z.ZodObject<
{
title: z.ZodOptional<z.ZodString>
description: z.ZodOptional<z.ZodString>
body: z.ZodOptional<z.ZodString>
tagList: z.ZodOptional<z.ZodArray<z.ZodString>>
status: z.ZodOptional<z.ZodEnum<{ draft: 'draft'; published: 'published' }>>
preserveSlug: z.ZodOptional<z.ZodBoolean>
metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>
},
z.core.$strip
>
Injection Notes
Requirements
Peer dependencies:
@molecule/api-database^1.0.1@molecule/api-i18n^1.0.1@molecule/api-logger^1.0.1@molecule/api-resource^1.5.1@molecule/api-resource-follow^1.0.5 (optional)@molecule/api-resource-reaction^1.0.3 (optional)@molecule/api-search^1.0.0 (optional)@molecule/api-slug^1.0.0express^5.0.0zod^4.0.0
Runtime Dependencies
-
@molecule/api-database -
@molecule/api-i18n -
@molecule/api-logger -
@molecule/api-resource -
@molecule/api-resource-follow(optional) -
@molecule/api-resource-reaction(optional) -
@molecule/api-search(optional) -
@molecule/api-slug -
express -
zod -
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 intoapi/migrations/yourself.src/__setup__/articles.sqlcreates thearticlesandarticle_tagstables;src/__setup__/articles_position.sqlandsrc/__setup__/articles_status.sqlupgrade pre-existing databases. When@molecule/api-resource-reactionor@molecule/api-resource-followare also installed, favorites (setFavorite) and followed-author feeds (getFeed) activate automatically; without them,articlesruns standalone withfavoritesCount: 0and no extra tables. -
article_tagskeeps the order the tags were given in, in itspositioncolumn (0-based). An app that reads the join table itself must order byposition— a submission-order assertion (tagList[0],tagList[1]) reads the wrong tag otherwise.Article.tagListis already in that order. -
Tags:
allTags()is every tag in use;popularTags(limit)is the top 20 by default. AGET /tagsendpoint (RealWorld'sGET /api/tags, which returns the whole list) built onpopularTags()with no argument drops every tag past the twentieth as soon as the database holds more than 20 — callallTags()for that endpoint, and pass alimitonly where the caller asked for the N most-used. The package's ownGET /articles/tagsroute does exactly this: no?limit=is the whole list. Catalog counts scan bounded pages through the bonded database; a provider's single-read safety cap never truncates the catalog or its popularity counts. -
Lists are newest first and paginated —
{ data, total, limit, offset }, at most 100 per page.createArticlestampscreatedAtstrictly increasing andupdateArticlealways movesupdatedAtforward, so newest-first order and a changedupdatedAthold even within one millisecond — an app never re-stamps these columns itself. -
Slugs are unique and stable. The first "Hello World" is
hello-world, the nexthello-world-2;feedandtagsare never used (they are routes). Changing the title updates the slug by default — passpreserveSlug: truetoupdateArticle(orPUT /articles/:slug) to keep published permalinks stable across title edits, or look up by immutable ID withgetArticleById. -
The author is the session user, always: create ignores any client author, and update/delete answer 403 to anyone else.
-
Drafts and publishing:
statusdefaults to'published'on create (settingpublishedAt). Passstatus: 'draft'to save an unpublished draft (publishedAt: null), and updatestatus: 'published'to publish it. Drafts are hidden from anonymous readers, other users, public feeds, and tag lists;GET /articles?status=draftor?status=allreturns the signed-in author's own drafts, andGET /articles/:slugreturns a draft only to its author. -
Search:
GET /articles?q=term(orlistArticles({ q })) performs a case-insensitive substring match acrosstitle,description,body, andtagList, composable withtag,authorId,favoritedBy,status, and pagination. -
Reads of published articles are public;
favoritedisfalsewithout a signed-in viewer. -
Article bodies are stored as given. Render markdown with
@molecule/app-markdown+ a provider (sanitized HTML) on the client. -
Comments on articles:
@molecule/api-resource-commentwith resource type'article'and the article id. Importing this package automatically registers an article visibility policy with@molecule/api-resource-commentso draft articles cannot receive comments and draft comments stay hidden from non-authors. An API whose comment ids are integers (RealWorld's) creates them withcreateNumberedCommentand finds them withgetCommentByNumber.
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:
- Publishing an article opens its page at the slug the API returned, and it shows first in the global list.
- Two articles with the same title get different slugs and both open.
- Filtering by a tag shows only articles with that tag.
- Favoriting increments the count, survives a reload, and unfavoriting brings it back; a signed-out visitor sees the count but no "favorited".
- The feed shows only articles by followed authors, and an empty feed shows a readable empty state.
- Only the author sees edit/delete; another user's direct attempt is refused.
- Deleting removes the article from every list after reload.