Skip to content

Backend Overview

Ankit Upadhyay edited this page Jul 24, 2026 · 2 revisions

Backend Overview

apps/backend is the single source of business logic — every client (web, mobile, desktop, developer API) calls it. Express + Prisma (Postgres), layered Router → Controller → Service → Model, with Zod/class-validator validation, Winston logging, and BullMQ jobs. The code under apps/backend/src is canonical.

Subsystem pages: Organizations & Companions · Appointments & Scheduling · Billing, Invoices, Subscriptions · Forms, E-Sign, Documents · Tasks, Observations, Inventory · Users, RBAC, Dashboard · Realtime, Chat, Jobs · Integrations · Testing.

Stack

Express 4.21, Prisma 5.22 over Postgres (@yosemite-crew/database), Zod + class-validator for validation, Winston logging, BullMQ jobs (Redis), Stripe, Stream Chat for realtime, plus AWS (S3, SES, Pinpoint), firebase-admin (push), and SuperTokens via @yosemite-crew/auth. (Mongoose was removed with the migration scaffold in PR #1819.)

Entry points

  • src/main.ts — startServer(): initQueues() → configureStreamUploadPolicy() → createApp() → app.listen(). Importing ./workers starts the BullMQ workers.
  • src/app.ts — createApp() builds the Express app: SuperTokens init (when enabled), helmet(), global rate limiting, raw-body webhook routes registered before express.json() (Stripe, Stripe Connect, Documenso, Finance, Stream), then file upload, CORS (dev only), JSON, mongo-sanitize, registerRoutes(app), /health, and the SuperTokens error handler.

The Router → Controller → Service → Model flow

All routers register in src/routers/index.ts via registerRoutes(app). Two namespace conventions:

  • /fhir/v1/<resource> — FHIR-facing resources (organization, companion, appointment, invoice, task, template, encounter, …), emitting/consuming FHIR R4 (@yosemite-crew/fhir).
  • /v1/<resource> — plain REST (document, stripe, finance, prescriptions, inventory, chat, notification, …).

A traced example — create an appointment from the PMS (POST /fhir/v1/appointment/pms):

flowchart LR
    R["appointment.router.ts<br/>requireWebAuth -> withOrgPermissions -> requirePermission"]
    C["appointment.prisma.controller.ts<br/>createFromPms (Zod parse)"]
    S["appointment.prisma.service.ts<br/>createAppointmentFromPms (prisma.$transaction)"]
    M[("Prisma models<br/>@yosemite-crew/database")]
    R --> C --> S --> M
Loading

Controllers parse/validate input and translate service errors to HTTP; services hold business logic (often in prisma.$transaction) and throw typed errors carrying a statusCode; models are Prisma.

Cross-cutting concerns

  • Validation — two coexisting styles: Zod schemas declared and .parse()d inside controllers/services (heaviest in FHIR/Prisma controllers), and class-validator DTOs via middlewares/validation.ts (validateAndSanitizeDTO(DTOClass)), with DTO classes in @yosemite-crew/types.
  • Auth — middlewares/auth.ts: requireWebAuth (web PIMS), requireMobileAuth (pet-parent mobile), and requireAnyAuth, all built on createSessionMiddleware from @yosemite-crew/auth (SuperTokens; provider selected via AUTH_PROVIDER, residual legacy Cognito/Firebase tokens accepted only under AUTH_LEGACY_TOKEN_GRACE). Landed via PR #1763. See Authentication and Identity.
  • RBAC — middlewares/rbac.ts: withOrgPermissions() resolves the caller's UserOrganization mapping and computes effective permissions; entity-scoped variants (withAppointmentOrgPermissions, withInvoiceOrgPermissions, …) derive the org from a resource id; requirePermission(...) enforces. See Users, RBAC, Dashboard.
  • Logging — utils/logger.ts, a Winston singleton (colorized in dev, JSON otherwise, circular-safe meta).
  • Error handling — no central REST error middleware; convention is try/catch per controller → logger.error → res.status(n).json({ message }), with services throwing typed errors that carry statusCode.
  • The Postgres/Mongo migration (completed) — the dual-write/read-switch scaffold (utils/dual-write.ts, config/read-switch.ts, the Mongoose models and dependency) was removed in PR #1819 (merged 2026-07-18); Postgres/Prisma is the sole system of record. Some domains still carry a legacy .service.ts sibling next to the active .prisma.service.ts. See Data Layer / ADR-0001.
  • Multi-tenant helpers — config/prisma.ts re-exports schema-per-tenant helpers (getTenantPrismaClient, registerTenant, …) from @yosemite-crew/database; see Multi-Tenancy and RBAC.

Directory map (src/)

app.ts, main.ts        entry / composition
routers/               one router per resource + index.ts registrar
controllers/           web/ (PMS) and app/ (mobile) controllers
services/              business logic (+ services/finance/, .prisma.service.ts variants)
models/                shared TS types + role-permission.ts (RBAC vocabulary)
middlewares/           auth.ts, rbac.ts, validation.ts, upload.ts
config/                auth-hooks, prisma, stream-upload-policy
integrations/          adapter registry (IDEXX, Merck)
labs/                  lab-order adapter registry (IDEXX)
queues/ + workers/     BullMQ
utils/                 logger, billing, scheduling, email, ...

Related

Product & Domain
Architecture
Applications
Design & Accessibility
Engineering Handbook
Decisions (ADRs)
Design Docs & Plans
Roadmap
Operations
Meta

Canonical code & docs: main repo · Auto-generated companion: DeepWiki

Clone this wiki locally