@molecule/api-resource-follow
v1.1.4
Published
Follow/unfollow users or any resource with polymorphic targeting
Maintainers
Readme
@molecule/api-resource-follow
Follow/unfollow resource for molecule.dev.
Polymorphic follow system for users or any resource type. Supports
followers list, following list, and follow status checks.
Use getFollowedIds(viewerId, targetType, ids) once per displayed collection, then
followed.has(id) for each item. It uses one query with no pagination truncation,
deduplicates ids, and does no I/O for an empty page or an absent viewer. It works for
any target type, including documents, topics and users. Use isFollowing for one target.
Custom routes use the same services. A profile route, username parameter or
different response envelope does not require the package's HTTP routes. Resolve
the username in the app, then call follow(viewerId, 'user', profile.id),
unfollow(viewerId, 'user', profile.id) or
isFollowing(viewerId, 'user', profile.id) and project the profile locally.
isFollowing accepts string | null | undefined; an absent viewer returns
false without a database read. Mutations still require an authenticated id.
These services use the package's follows table, with followerId, targetType
and targetId. For users, targetId is the canonical user id, never the username.
A genuinely different relationship schema stays local; these calls do not read a
custom followingId column or a separate table.
import { getFollowedIds } from '@molecule/api-resource-follow'
export async function projectWatchedNotes(
notes: readonly { id: string; title: string }[],
viewerId?: string | null,
) {
const followed = await getFollowedIds(
viewerId,
'note',
notes.map(({ id }) => id),
)
return notes.map((note) => ({ ...note, watching: followed.has(note.id) }))
}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-follow'
// Wire routes into your Express app via mlcl inject
// POST /follow/:targetType/:targetId
// DELETE /follow/:targetType/:targetId
// GET /:targetType/:targetId/followers
// GET /following
// GET /follow/check/:targetType/:targetIdimport { isFollowing } from '@molecule/api-resource-follow'
// The app resolves a username to this public profile before projecting it.
async function projectProfile(
profile: { id: string; username: string; bio: string | null; avatar: string | null },
viewerId: string | null | undefined,
) {
return {
username: profile.username,
bio: profile.bio,
image: profile.avatar,
following: await isFollowing(viewerId, 'user', profile.id),
}
}Type
resource
Installation
npm install @molecule/api-resource-follow @molecule/api-database @molecule/api-i18n @molecule/api-loggerAPI
Interfaces
Follow
A follow relationship between a user and a target resource.
interface Follow {
/** Unique follow identifier. */
id: string
/** The ID of the user who is following. */
followerId: string
/** The type of target being followed (e.g. 'user', 'project'). */
targetType: string
/** The ID of the target being followed. */
targetId: string
/** When the follow was created (ISO 8601). */
createdAt: string
/** When the follow was last updated (ISO 8601). */
updatedAt: 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
}Functions
create(req, res)
Creates a follow relationship. Idempotent.
function create(req: MoleculeRequest, res: MoleculeResponse): Promise<void>req— The request withtargetTypeandtargetIdparams.res— The response object.
del(req, res)
Removes a follow relationship.
function del(req: MoleculeRequest, res: MoleculeResponse): Promise<void>req— The request withtargetTypeandtargetIdparams.res— The response object.
list(req, res)
Lists paginated followers of a target.
function list(req: MoleculeRequest, res: MoleculeResponse): Promise<void>req— The request withtargetTypeandtargetIdparams.res— The response object.
following(req, res)
Lists targets the current user is following.
function following(req: MoleculeRequest, res: MoleculeResponse): Promise<void>req— The request with pagination query params.res— The response object.
checkFollowing(req, res)
Checks if the current user is following a target.
function checkFollowing(req: MoleculeRequest, res: MoleculeResponse): Promise<void>req— The request withtargetTypeandtargetIdparams.res— The response object.
follow(followerId, targetType, targetId)
Creates a follow relationship. Idempotent — returns existing follow if already following.
targetId is stored exactly as supplied: the package does not resolve a
username or display handle to an id, and does not require the target to
exist. For targetType 'user', pass the target's user id — the same
identity the rest of the app keys that user's rows by (an app using
@molecule/api-resource-article's feed stores that id in articles.authorId,
which the feed matches against targetId); a route that receives a username
resolves it first. For any other targetType, the canonical id is whatever
the app's own reader of that resource uses. Pass the SAME value to
unfollow and isFollowing, or those calls target a different follow.
function follow(followerId: string, targetType: string, targetId: string): Promise<Follow>followerId— The ID of the follower.targetType— The type of target being followed.targetId— The target's canonical id. For'user', the user id, not a username or display handle.
Returns: The created or existing follow.
unfollow(followerId, targetType, targetId)
Removes a follow relationship.
function unfollow(followerId: string, targetType: string, targetId: string): Promise<void>followerId— The ID of the follower.targetType— The type of target.targetId— The ID of the target.
getFollowers(targetType, targetId, options)
Gets paginated followers of a target.
function getFollowers(
targetType: string,
targetId: string,
options?: PaginationOptions,
): Promise<PaginatedResult<Follow>>targetType— The type of target.targetId— The ID of the target.options— Pagination options.
Returns: Paginated followers.
getFollowing(userId, options)
Gets paginated targets a user is following.
function getFollowing(userId: string, options?: PaginationOptions): Promise<PaginatedResult<Follow>>userId— The follower's user ID.options— Pagination options.
Returns: Paginated follows.
isFollowing(followerId, targetType, targetId)
Checks if a viewer is following a target. An absent viewer returns false without I/O.
function isFollowing(
followerId: string | null | undefined,
targetType: string,
targetId: string,
): Promise<boolean>followerId— The viewer's user ID, or no viewer for public content.targetType— The type of target.targetId— The ID of the target.
Returns: true if following.
getFollowedIds(followerId, targetType, targetIds)
Load a viewer's follow state for a collection in one query, rather than one per item.
Targets are canonical ids, exactly as with follow and isFollowing. Repeated ids are
deduplicated. An absent viewer or empty collection does no I/O. There is no cross-call cache.
The result contains only followed ids from this collection, for this viewer and target type.
function getFollowedIds(
followerId: string | null | undefined,
targetType: string,
targetIds: readonly string[],
): Promise<Set<string>>followerId— The viewer's user id, or no viewer for public content.targetType— The resource type being followed.targetIds— Canonical ids referenced by the collection.
Returns: The subset of target ids this viewer follows.
getFollowerCount(targetType, targetId)
Gets the follower count for a target.
function getFollowerCount(targetType: string, targetId: string): Promise<number>targetType— The type of target.targetId— The ID of the target.
Returns: The number of followers.
getFollowingCount(userId)
Gets the following count for a user.
function getFollowingCount(userId: string): Promise<number>userId— The user ID.
Returns: The number of targets the user is following.
Constants
requestHandlerMap
Handler map for follow routes.
const requestHandlerMap: {
readonly create: typeof create
readonly del: typeof del
readonly list: typeof list
readonly following: typeof following
readonly checkFollowing: typeof checkFollowing
}routes
Routes for follow/unfollow, followers, following, and status check.
const routes: readonly [
{
readonly method: 'post'
readonly path: '/follow/:targetType/:targetId'
readonly handler: 'create'
readonly middlewares: readonly ['authenticate']
},
{
readonly method: 'delete'
readonly path: '/follow/:targetType/:targetId'
readonly handler: 'del'
readonly middlewares: readonly ['authenticate']
},
{
readonly method: 'get'
readonly path: '/:targetType/:targetId/followers'
readonly handler: 'list'
},
{
readonly method: 'get'
readonly path: '/following'
readonly handler: 'following'
readonly middlewares: readonly ['authenticate']
},
{
readonly method: 'get'
readonly path: '/follow/check/:targetType/:targetId'
readonly handler: 'checkFollowing'
readonly middlewares: readonly ['authenticate']
},
]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.0.1 (optional)
Runtime Dependencies
@molecule/api-database@molecule/api-i18n@molecule/api-logger@molecule/api-resource(optional)List endpoints return a PAGINATED envelope
{ data, total, limit, offset }, not a bare array — read the rows offresult.data(server). On the client,unwrapList(res)from@molecule/app-httpnormalizes this envelope (pass it the whole HttpResponse), so the rows come back; reading the response as a bare array — orres.dataalone (which is the envelope) — yields an EMPTY list. A scaffold that lists this package already has this table: its__setup__SQL is copied into the app at create time and replayed on every boot, so do not copy it intoapi/migrations/yourself — only a package added after the scaffold needs that.src/__setup__/follows.sqlcreates the singlefollowstable. An mlcl-scaffolded API replays__setup__/*.sqlon migrate (aCREATE TABLE IF NOT EXISTS, so a table the app's own migrations already create keeps only its own columns: ALTER in the ones it lacks); anywhere else run it once — nothing at runtime creates it.
The follower is ALWAYS the authenticated user: handlers read
res.locals.session (populated by your global auth middleware) and 401
without it — never accept a follower userId from the body or params.
GET /:targetType/:targetId/followers is deliberately PUBLIC; gate it
yourself if follower lists are private in your app.
targetType is a free-form string (user, post, …) — the package does
not validate it against your schema, so constrain accepted values in your
app if arbitrary types would be a problem.
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:
- [ ] User A follows user B (
POST /follow/user/:B): B's follower count and A's following count each increment by exactly one, B appears in A's following list (GET /following) and A appears in B's followers list (GET /user/:B/followers). Reload — the edge and both counts persist (it's a realfollowsrow, not local UI state). - [ ] Following is IDEMPOTENT: A following B a second time (double-tap Follow
or replay the POST) creates NO duplicate edge and does NOT double-count —
exactly one
followsrow exists for (A → B) and both counts are unchanged. - [ ] Unfollow (
DELETE /follow/user/:B) removes the edge: A's following count and B's follower count each decrement back, B leaves A's following list, A leaves B's followers, andGET /follow/check/user/:Bnow returns{ following: false }. - [ ] You cannot follow yourself: the UI never offers Follow on your own
profile, and following your own id never inflates your own counts. This
package's
follow()does not rejectfollowerId === targetId, so the app must guard it — verify the guard exists, don't assume it. - [ ] AUTHORIZATION — the follower is ALWAYS the session user: handlers read
res.locals.sessionand 401 without it, so no UI or endpoint lets you follow/unfollow on behalf of another user by passing their id, and follow/unfollow act only on your own edges. Signed in as A you can never make B follow or unfollow anyone.
