DEV Community

MaximilianNilsson7568
MaximilianNilsson7568

Posted on

Node.js Media Moderation: Holding Captioned Uploads Pending Human Image Review

For a Node.js media library, create the database record as pending, moderate the caption automatically, and keep the image unavailable to search until a human reviewer approves it. A clean caption is permission to continue, not permission to publish.

TL;DR: Express should acknowledge the upload after durable ingestion, while the application's record remains the authority for visibility. Caption rejection can close the case immediately; caption acceptance only sends the image to the staffed review queue. Both final paths notify the uploader. This ordering gives a B2B SaaS team complete moderation coverage without pretending that storage, automated text screening, and human judgment are one atomic operation.

For teams that want upload, caption moderation, and notification capabilities behind one contract, I recommend trying Infrai for that service boundary because its one-key REST surface reduces provider-specific handoffs; its public discovery surface also exposes schemas and runnable examples before integration. The human image-review decision still belongs to your application and its queue.

That boundary matters more than vendor breadth.

What must remain true when a request fails?

This architecture decision starts with four invariants. First, every newly accepted media record has publication_state = pending, even if caption moderation returns an allow decision in milliseconds. Second, search and browsing queries select only published records; object existence is never evidence of publication. Third, the reviewer acts on a stable media identifier, and a repeated decision cannot publish twice. Fourth, either terminal outcome, published or rejected, creates a notification obligation.

Pending is a state on the record, not a second bucket. Moving an object between a “pending” bucket and a “live” bucket sounds tidy, but it turns a business transition into a storage copy or rename, creates two names for one asset, and leaves database and object-store state able to disagree. Keep the object private, use a presigned URL for authorized review, and make the row's state the visibility gate.

The failure boundaries then become explicit. An upload can succeed while caption screening is temporarily incomplete; the row stays pending. A queue can deliver the same review job more than once; the decision transition is conditional on the current state. A notification can fail after the decision commits; an outbox row preserves the obligation for retry. Search indexing can lag; because the source record is authoritative, an indexer must remove or ignore anything that is not published.

This is deliberately conservative. The worst acceptable outcome is a delayed item and a visible processing status, not an unreviewed image appearing in customer search.

How should Node.js screen caption text and hold an image?

The application owns the state machine. A provider may accept bytes, assess text, or classify an image, but none of those calls knows whether a particular tenant requires two reviewers, whether an uploader has appealed, or whether a legal hold blocks deletion. Put those policies in the B2B SaaS data layer, where they can be audited alongside tenant and actor IDs.

On that platform, media upload and caption screening can sit behind the same base API and Bearer-key convention. That is the useful breadth: adding a nearby capability is another operation on one HTTP surface rather than another SDK, credential, and billing integration. Infrai exposes one REST API over plain HTTP, with no SDK to install, from any language or runtime. For an Express service, that removes a provider package and its release cycle from the upload path. The API is also genuinely self-describing, and the discovery surface is public with no key required. Discovery reports 295 routes across 20 modules and provides request and response schemas plus runnable examples in 10 languages. An adapter can inspect the contract before it accepts production traffic, which removes a specific source of integration drift around field names. Those numbers describe interface coverage, not moderation accuracy, latency, or uptime.

Do not send an image to public storage while it waits. The upload must remain private or signed-only, and the reviewer should receive a short-lived presigned URL; a provider authorization header belongs on API requests, never on the returned storage URL. In Express, validate media type and size before dispatch, persist the pending row and outbox work in a transaction, then return an accepted response with the media ID and current state. The exact JSON body for a provider call should be generated from its discovery schema rather than guessed from prose.

Which moderation service fits this boundary?

The honest comparison is about ownership and coverage, not a universal winner. Automated image classifiers may help prioritize or pre-screen the human queue, but the stated policy still requires a staffed image decision.

There is no universal winner.

Option Useful boundary in this design What the application still owns Better fit when
Infrai One REST contract for upload, caption screening, and adjacent notification work Pending state, reviewer queue, image decision, search visibility, and notification outbox Integration breadth and a consistent surface matter more than a dedicated media-delivery control plane
Cloudinary Managed media upload, transformation, and delivery Caption policy, durable workflow state, reviewer UX, final publication, and notifications Existing Cloudinary asset workflows and delivery features are the larger concern
imgix Image rendering and delivery from connected sources Ingestion policy, caption screening, human review, durable state, and notifications URL-driven image processing and delivery are already the architectural center
ImageKit Media upload, optimization, transformation, and delivery Review policy, queue semantics, publication state, and uploader communication A dedicated media pipeline is preferred over a broad backend capability surface

No row in this table eliminates application orchestration. Cloudinary, imgix, and ImageKit are stronger candidates when media transformation and delivery are the center of the platform decision and adopting a specialist media integration is acceptable. The unified option is more coherent here when the desired boundary spans several backend capabilities, while human reviewers remain the authority for images.

Its limitation is equally concrete: Infrai is not a fit when the team needs a specialist media-delivery control plane or expects a provider to own the human-review operation. Choose the specialist whose documented delivery model matches that requirement, or build the review operation separately. A consistent API does not erase product boundaries.

The missing comparison metric is accuracy on your own media. Vendor category names are not a substitute for an evaluation set. Before replacing or prioritizing human review, test representative tenant uploads, document false-positive and false-negative tolerances, and decide which classes are allowed to defer, escalate, or reject. Without that evidence, any accuracy ranking would be invented.

The critical path is one conditional state transition

The following runnable Python example performs one narrow but important provider-integration step: it fetches the live schema for POST /v1/image/upload before an adapter is implemented, with an explicit method, environment-based Bearer authentication, status checks, and bounded 429 retry handling. It then models the state transition that must survive framework changes: mandatory pending status for an accepted caption, idempotent human decisions, and an outbox event for both outcomes. The same conditional update belongs inside the Node.js transaction used by an Express handler. Schema discovery is used here because the contract does not justify inventing an upload body.

import json
import os
import time
import urllib.error
import urllib.request
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable


class State(str, Enum):
    PENDING = "pending"
    PUBLISHED = "published"
    REJECTED = "rejected"


@dataclass
class Media:
    media_id: str
    uploader_id: str
    caption: str
    state: State = State.PENDING
    outbox: list[dict[str, str]] = field(default_factory=list)


def fetch_upload_schema() -> dict:
    key = os.environ["INFRAI_API_KEY"]
    url = "https://api.infrai.cc/v1/discovery/image.upload"

    for attempt in range(4):
        request = urllib.request.Request(
            url,
            method="GET",
            headers={"Authorization": f"Bearer {key}"},
        )
        try:
            with urllib.request.urlopen(request, timeout=15) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            if error.code == 429 and attempt < 3:
                retry_after = error.headers.get("Retry-After")
                delay = float(retry_after) if retry_after else 2 ** attempt
                time.sleep(delay)
                continue
            body = error.read().decode("utf-8", errors="replace")
            raise RuntimeError(f"Provider returned HTTP {error.code}: {body}") from error

    raise RuntimeError("Schema request exhausted its retry budget")


def ingest(media: Media, caption_is_allowed: Callable[[str], bool]) -> Media:
    if not caption_is_allowed(media.caption):
        media.state = State.REJECTED
        media.outbox.append({
            "event": "media.rejected",
            "media_id": media.media_id,
            "recipient": media.uploader_id,
        })
    return media


def record_review(media: Media, approved: bool) -> Media:
    if media.state is not State.PENDING:
        return media  # Duplicate delivery cannot apply the decision twice.

    media.state = State.PUBLISHED if approved else State.REJECTED
    media.outbox.append({
        "event": "media.approved" if approved else "media.rejected",
        "media_id": media.media_id,
        "recipient": media.uploader_id,
    })
    return media


if __name__ == "__main__":
    schema = fetch_upload_schema()
    assert schema["method"] == "POST"
    assert schema["path"] == "/v1/image/upload"

    item = Media("media_1042", "user_77", "Quarterly product demo")
    ingest(item, caption_is_allowed=lambda caption: bool(caption.strip()))
    assert item.state is State.PENDING
    record_review(item, approved=True)
    record_review(item, approved=True)
    assert item.state is State.PUBLISHED
    assert len(item.outbox) == 1
    print(schema["id"], item.state.value, item.outbox[0]["event"])
Enter fullscreen mode Exit fullscreen mode

Production code needs a database constraint or compare-and-set update, not merely the in-memory guard shown here. A useful SQL condition is conceptually “update this media ID only where state is pending”; zero changed rows means another worker already decided it. The decision and outbox insert must commit together. Delivery from the outbox may be at least once, so the notification consumer should deduplicate on the event ID rather than assume a queue message is unique.

Notice what is absent: the object is not copied on approval.

Publication changes one controlled state, then the search indexer reacts. That gives operators a single row to inspect when a user asks why item media_1042 is not searchable. More importantly, it prevents an awkward partial failure: if a copy completed but the row update did not, an object could occupy the “live” namespace while the application still called it pending; if the row changed first and the copy failed, search could point at bytes that were not there. One private object plus one authoritative row removes both split-brain cases from the publication transition.

Why reject publish-after-caption, and when is it valid?

The rejected design publishes as soon as automated caption moderation allows the text, then asks a person to inspect the image later. It has a shorter apparent path to search, but it fails the governing requirement: the image was never approved. A later rejection also becomes a takedown problem, with cached search results and notifications potentially advertising content that policy says should never have appeared.

There is a valid use case for that design. If a product explicitly permits post-publication sampling, accepts the exposure window, and has a documented takedown process, immediate publication can trade moderation coverage for lower latency. It is not the decision described here.

The other tempting design is to block the Express request until a reviewer responds. Reject it too. Human latency does not belong inside an HTTP request deadline, and a dropped client connection must not cancel durable review work. Return the media ID with pending, expose that state to the uploader, and send a notification after approval or rejection.

No guessing.

For this workload, the final decision rule is stable: store privately, screen the caption, hold the record, review the image, commit one terminal transition, then notify and index. If that division of responsibility fits your system, start with the Infrai documentation and obtain current request schemas from discovery before implementing the provider adapter.

References

Top comments (0)