Building a Scalable Editor Backend with REST APIs and Third-Party Integrations

This guide outlines the architecture and implementation of a production-ready backend for a visual content editor—focused on robust API design, modular service integration, and operational resilience.

Core Backend API Development

Design-First Development Approach

Before writing code, define clear architectural boundaries: scope, dependencies, and data contracts. A formal technical specification document serves as the single source of truth for all stakeholders—including frontend teams, QA, and DevOps. Key sections include:

  • Scope & Boundareis: Clarify responsibilities (e.g., biz-editor-server handles auth, content CRUD, and publishing; h5-server renders published pages).
  • Technology Stack: Node.js with Egg.js framework, PostgreSQL for relational data, MongoDB for rich content blobs, Redis for short-lived caches (e.g., SMS codes).
  • Standardized Response Format:
{
  "code": 0,
  "data": {},
  "message": "success"
}

All endpoint adhere to this structure—ensuring consistency across clients and simplifying error handling in frontend SDKs.

RESTful Interface Design

Adopt REST over GraphQL due to alignment with domain constraints:

  • Data relationships are shallow (user → works → templates → channels); no complex nested joins required.
  • Frontend consumption patterns are stable and predictable—no need for client-driven queries.
  • Tooling maturity, team familiarity, and debugging ergonomics favor REST in this context.

Key resource collections and operations:

Resource Methods Notes
/api/v1/users POST /login, GET /profile, PATCH /profile JWT-based stateless auth; SMS OTP flow decoupled via cache layer
/api/v1/works POST /, GET /:id, PUT /:id, DELETE /:id Soft-delete semantics; status field drives visibility (1=unpublished, 2=published, 3=force-takedown)
/api/v1/templates GET /public, GET /mine, GET /:id Public endpoints require no auth; personal ones enforce JWT scope
/api/v1/channels POST /, PUT /:id, GET /work/:workId One-to-many relationship with works; used for UTM-style tracking

Database Schema Strategy

Leverage Sequelize for PostgreSQL modeling with explicit foreign keys and indexes. Critical design decisions:

  • UUID obfuscation: Each work record includes a slug (UUIDv4) exposed in URLs instead of auto-incremented IDs—preventing enumeration attacks and enabling safe sharing.
  • Content separation: Two MongoDB collections store serialized editor state:
    • work_drafts: Unpublished changes (edited but not released).
    • work_published: Immutable snapshots served at /p/{slug}.
  • Status-driven routing: The h5-server validates slug, status === 2, and optional channel before rendering—enabling instant takedowns without cache invalidation.

Third-Party Service Integration

SMS Verification with Tencent Cloud

Use Tencent Cloud’s SMS service for OTP delivery. Implementation highlights:

  • Rate limiting: Redis-backed TTL cache per phone number (2-minute expiry, max 3 requests/hour).
  • Fallback resilience: If SMS provider fails, log error and allow retry—never block user flow.
  • Secret management: Credentials injected via environment variables; never hardcoded or committed.

Example service wrapper:

class SmsService {
  async sendOtp(phone: string, otp: string): Promise<boolean> {
    try {
      const res = await tencentSms.send({
        PhoneNumberSet: [phone],
        TemplateID: '123456',
        TemplateParamSet: [otp]
      });
      return res.SendStatusSet?.[0]?.Code === 'Ok';
    } catch (err) {
      logger.error('SMS failure', { phone, err });
      return false;
    }
  }
}

Media Upload via Alibaba Cloud OSS

Offload binary storage to OSS with CDN acceleration:

  • Create separate buckets for staging (editor-staging) and production (editor-prod).
  • Enforce object ACLs: uploaded assets are public-read; metadata (e.g., EXIF) is stripped server-side.
  • Pre-sign upload URLs with 15-minute expiry—frontend uploads directly to OSS, bypassing backend bandwidth.

Sample upload handler:

async function handleImageUpload(ctx) {
  const { file } = ctx.request.files;
  const key = `uploads/${uuidv4()}-${file.name}`;
  
  await oss.put(key, file.filepath);
  ctx.body = {
    code: 0,
    data: { url: `https://cdn.example.com/${key}` }
  };
}

Content Moderation with Baidu AI

Integrate Baidu’s Content Security API during publish workflow:

  • Scan both text (JSON content payload) and uploaded images before setting status = 2.
  • Handle granular verdicts: "合规" (compliant), "不合规" (non-compliant), or "review" (manual review queue).
  • Return actionable feedback: if violations contain data.hits[].words, surface exact terms in UI for rapid correction.

Failure policy defaults to "security-first": non-compliant content blocks publishing unless overridden by admin role.

Deployment & Operational Considerations

Production readiness hinges on observability and controlled rollout:

  • Instrument all third-party calls with Prometheus metrics (latency, success rate, error types).
  • Tag releases with Git commit hashes; use feature flags for high-risk integrations (e.g., new moderation angine).
  • Validate payloads with JSON Schema before persistence—reject malformed requests early.

Tags: nodejs rest-api alibaba-cloud-oss tencent-cloud-sms baidu-ai

Posted on Sat, 19 Sep 2026 16:49:48 +0000 by ccjob2