npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@molecule/api-resource-reaction

v1.1.2

Published

Like/emoji reactions on any resource with polymorphic attachment

Readme

@molecule/api-resource-reaction

Like/emoji reactions resource for molecule.dev.

Polymorphic reactions that attach to any resource type. Supports multiple reaction types (like, love, laugh, etc.) with idempotent add/remove.

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-reaction'

// Wire routes into your Express app via mlcl inject
// POST   /:resourceType/:resourceId/reactions
// DELETE /:resourceType/:resourceId/reactions
// GET    /:resourceType/:resourceId/reactions

Type

resource

Installation

npm install @molecule/api-resource-reaction @molecule/api-database @molecule/api-i18n @molecule/api-logger zod

API

Interfaces

ReactionResourceAccessContext

Context passed to a registered parent-resource access policy.

interface ReactionResourceAccessContext {
  /** The polymorphic parent resource type (e.g. `'article'`, `'post'`, `'project'`). */
  resourceType: string
  /** The polymorphic parent resource identifier. */
  resourceId: string
  /** Whether the caller is reading/removing (`'read'`) or adding (`'create'`) a reaction. */
  action: ReactionResourceAction
  /** The signed-in user ID, or `null`/`undefined` for anonymous callers. */
  viewerId?: string | null
}

Reaction

A reaction attached to a resource by a user.

interface Reaction {
  /** Unique reaction identifier. */
  id: string
  /** The type of resource this reaction is on (e.g. 'post', 'comment'). */
  resourceType: string
  /** The ID of the resource this reaction is on. */
  resourceId: string
  /** The ID of the user who reacted. */
  userId: string
  /** The reaction type (e.g. 'like', 'love', 'laugh'). */
  type: string
  /** When the reaction was created (ISO 8601). */
  createdAt: string
  /** When the reaction was last updated (ISO 8601). */
  updatedAt: string
}

ReactionSummary

Summary of reactions on a resource, with counts per type and user reactions.

interface ReactionSummary {
  /** Total number of reactions across all types. */
  total: number
  /** Count of reactions per type. */
  counts: Record<string, number>
  /** The reaction types from the current user, if any. */
  userReactions: string[]
}

Types

ReactionResourceAction

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

type ReactionResourceAction = 'read' | 'create'

ReactionResourceAccessCheck

Predicate deciding whether a viewer may read or add reactions on a parent resource.

type ReactionResourceAccessCheck = (
  context: ReactionResourceAccessContext,
) => boolean | Promise<boolean>

DefaultReactionType

A default reaction type string.

type DefaultReactionType = (typeof DEFAULT_REACTION_TYPES)[number]

Classes

ReactionResourceAccessError

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

class ReactionResourceAccessError 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 reaction'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 reactions: ${resourceType}/${resourceId}`)
    this.name = 'ReactionResourceAccessError'
    this.resourceType = resourceType
    this.resourceId = resourceId
  }
}

Functions

registerReactionResourceAccessPolicy(resourceType, check)

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

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

unregisterReactionResourceAccessPolicy(resourceType)

Removes a previously registered parent-resource access policy.

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

clearReactionResourceAccessPolicies()

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

function clearReactionResourceAccessPolicies(): void

getReactionResourceAccessPolicy(resourceType)

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

function getReactionResourceAccessPolicy(
  resourceType: string,
): ReactionResourceAccessCheck | undefined
  • resourceType — Canonical resource type slug.

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

hasReactionResourceAccessPolicies()

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

function hasReactionResourceAccessPolicies(): boolean

Returns: Whether any access policy is active.

canAccessReactionResource(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 canAccessReactionResource(
  resourceType: string,
  resourceId: string,
  action: ReactionResourceAction,
  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.

create(req, res)

Adds a reaction to a resource. Idempotent — adding the same reaction type twice returns the existing reaction.

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

del(req, res)

Removes a user's reaction from a resource. Optionally removes only a specific reaction type via query parameter.

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

list(req, res)

Returns a reaction summary for a resource, including counts per type and the current user's reactions (if authenticated).

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

addReaction(resourceType, resourceId, userId, type)

Adds a reaction to a resource. If the user already has the same reaction type on this resource, returns the existing one (idempotent).

function addReaction(
  resourceType: string,
  resourceId: string,
  userId: string,
  type: string,
): Promise<Reaction>
  • resourceType — The type of resource being reacted to.
  • resourceId — The ID of the resource being reacted to.
  • userId — The ID of the reacting user.
  • type — The reaction type (e.g. 'like', 'love').

Returns: The created or existing reaction.

removeReaction(resourceType, resourceId, userId, type)

Removes a user's reaction from a resource. If type is provided, removes only that reaction type. Otherwise, removes all reactions by the user on the resource.

function removeReaction(
  resourceType: string,
  resourceId: string,
  userId: string,
  type?: string,
): Promise<void>
  • resourceType — The type of resource.
  • resourceId — The ID of the resource.
  • userId — The ID of the user.
  • type — Optional specific reaction type to remove.

getReactionSummary(resourceType, resourceId, userId)

Gets a reaction summary for a resource, including counts per type and the current user's reactions.

function getReactionSummary(
  resourceType: string,
  resourceId: string,
  userId?: string,
): Promise<ReactionSummary>
  • resourceType — The type of resource.
  • resourceId — The ID of the resource.
  • userId — Optional current user ID to include their reactions.

Returns: A reaction summary with total, counts, and user reactions.

getUserReactions(resourceType, resourceId, userId)

Gets the current user's reaction on a resource, if any.

function getUserReactions(
  resourceType: string,
  resourceId: string,
  userId: string,
): Promise<Reaction[]>
  • resourceType — The type of resource.
  • resourceId — The ID of the resource.
  • userId — The user ID.

Returns: The user's reactions on this resource.

getReactionCounts(resourceType, resourceId)

Gets reaction counts per type for a resource.

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

Returns: A record of reaction type to count.

Constants

requestHandlerMap

Handler map for reaction routes.

const requestHandlerMap: {
  readonly create: typeof create
  readonly del: typeof del
  readonly list: typeof list
}

routes

Routes for reaction add/remove/summary.

const routes: readonly [
  {
    readonly method: 'post'
    readonly path: '/:resourceType/:resourceId/reactions'
    readonly handler: 'create'
    readonly middlewares: readonly ['authenticate']
  },
  {
    readonly method: 'delete'
    readonly path: '/:resourceType/:resourceId/reactions'
    readonly handler: 'del'
    readonly middlewares: readonly ['authenticate']
  },
  {
    readonly method: 'get'
    readonly path: '/:resourceType/:resourceId/reactions'
    readonly handler: 'list'
  },
]

DEFAULT_REACTION_TYPES

Default reaction types supported out of the box.

const DEFAULT_REACTION_TYPES: readonly ['like', 'love', 'laugh', 'wow', 'sad', 'angry']

addReactionSchema

Schema for validating reaction creation/toggle input.

const addReactionSchema: z.ZodObject<{ type: z.ZodString }, z.core.$strip>

removeReactionSchema

Schema for validating reaction removal input.

const removeReactionSchema: z.ZodObject<{ type: z.ZodOptional<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 (optional)
  • zod ^4.0.0

Runtime Dependencies

  • @molecule/api-database
  • @molecule/api-i18n
  • @molecule/api-logger
  • @molecule/api-resource (optional)
  • zod

Session-auth prerequisite: create and del read the caller from res.locals.session.userId and fail closed with 401 — mount the routes behind your global auth middleware (the declared authenticate middleware string). Reactions are always owner-scoped: handlers derive the reacting user from the SESSION, never from the request body, and del removes only the caller's own reactions (optionally a single type via ?type=).

The GET summary route is PUBLIC by default (no authenticate) so anonymous visitors can see counts; when a session is present it also includes the current user's reactions. create, del, and list enforce any parent-resource access policy registered via registerReactionResourceAccessPolicy (sharing the Symbol.for('@molecule/api-resource/access-policies') registry with @molecule/api-resource-comment and @molecule/api-resource-article): when denied, handlers return 404 and addReaction runs the policy check and insert atomically inside a database transaction when supported by the bonded pool. Sibling resources like @molecule/api-resource-article register draft visibility automatically on import.

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 into api/migrations/ yourself — only a package added after the scaffold needs that. src/__setup__/reactions.sql creates reactions (unique per (resourceType, resourceId, userId, type) — add is idempotent). An mlcl-scaffolded API replays __setup__/*.sql on migrate (a CREATE 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 them.

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:

  • [ ] Reacting to a target (POST .../reactions with a type) adds the user's reaction: the summary's counts[type] and total each increment by exactly one and the button shows the active state in the UI.
  • [ ] It is idempotent — the SAME user reacting again with the SAME type does NOT double-count: the repeat POST returns the existing reaction and counts[type] is unchanged. A single user can inflate a type's count by at most one, however many times they tap.
  • [ ] Switching reaction type (e.g. 👍 → ❤️) MOVES the user's reaction — old type −1, new type +1 — it does NOT leave both. Uniqueness is per (resourceType, resourceId, userId, type), so a raw add of the new type just stacks a second reaction; the switch UI must remove the prior type (DELETE ?type=) before adding the new one — verify it doesn't stack two.
  • [ ] Un-reacting decrements correctly: DELETE ?type= removes only that type (its counts[type]/total drop by one), DELETE with no type clears all of the user's reactions on the target, and deleting a reaction the user never made is a no-op — counts never go negative.
  • [ ] The summary reflects reality after each action: counts per type, total, the current user's userReactions, and any "who reacted" list all match exactly what was added/removed — reload and re-check.
  • [ ] Authorization: the reactor is ALWAYS the session user — the reacting userId comes from res.locals.session, never the request body, so a caller cannot react as someone else by supplying an id; a user can remove only their OWN reaction; POST/DELETE require an authenticated session (401 without) while the GET summary is public; and since this package does not verify target visibility, reacting must be reachable only for resources the user may see — gate the routes behind the parent resource's own access check.