Projects/Thrift E-Commerce Platform/Architecture & testing

Thrift platform architecture

A Functional DDD and Hexagonal backend, ten bounded contexts, and a testing strategy built around a pure domain core.

On this page

Status: Thrift is still heavily under development. APIs, schema, and UI may change.

Thrift is a full-stack e-commerce marketplace for new, used, and antique items. The platform combines a public storefront with vendor administration, product variants, carts, orders, analytics, payments, media, and reviews.

The backend is the interesting part: it is structured as Functional Domain-Driven Design + Hexagonal Architecture. Business rules are pure functions with no I/O; everything else lives in a thin imperative shell.

Overview

The repository is a pnpm workspace with four packages:

PackageResponsibility
thrift-apiExpress + TypeScript REST API, domain logic, persistence, auth, payments, and jobs.
thrift-webNext.js storefront, product pages, cart, and vendor dashboard.
cron-jobsScheduled maintenance and reporting tasks.
thrift-classical-searchDedicated product search and indexing service.

The API is split into ten bounded contexts behind a shared kernel of Result, DomainError, Money, and domain-event primitives.

Stack

  • Monorepo: pnpm workspaces
  • Backend: Node.js 20+ (CI runs Node 22), Express, TypeScript, PostgreSQL, Supabase, Knex
  • Frontend: Next.js, React, TypeScript, Tailwind CSS, shadcn/ui, Jotai
  • Integrations: Supabase Auth, Paystack, Upstash QStash, Cloudinary
  • Testing: Mocha, Chai, local Supabase, and a real HTTP test server

Monorepo layout

text
1packages/
2 thrift-api/
3 src/context/ # ten bounded contexts
4 src/shared/ # Result, DomainError, Money, events
5 src/routes/ # Express wiring
6 src/db/ # Knex and Postgres infrastructure
7 src/app-schema/ # Joi request/response schemas
8 src/tests/ # unit, integration, adversarial
9 thrift-web/ # customer and vendor web app
10 cron-jobs/ # scheduled work
11 thrift-classical-search/ # search and indexing

Functional DDD + Hexagonal

The design goal is simple: business rules should not know about Express, Knex, or the network.

mermaid
HTTP handlerUse caseDomain smart constructorRepository portKnex adapterPostgreSQLExternal service portSupabase / Paystack /QStash / Cloudinary
View source
flowchart TD
  H[HTTP handler] --> A[Use case]
  A --> D[Domain smart constructor]
  D --> P[Repository port]
  P --> I[Knex adapter]
  I --> DB[PostgreSQL]
  A --> E[External service port]
  E --> X[Supabase / Paystack / QStash / Cloudinary]

Each context uses the same layering:

LayerResponsibilityAllowed to import
domain/Aggregates, value objects, invariants.Nothing framework-specific.
application/Curried use cases returning Result<…, DomainError>.domain/ and ports/ only.
ports/Repository and external-service contracts.Types and domain primitives.
infra/Knex and external-service adapters.ports/ and database tooling.
http/Request parsing, authorization, and transport mapping.application/ and shared HTTP errors.

A smart constructor is the only way to create a valid aggregate. For example, createProduct rejects missing titles, invalid categories, empty variant lists, duplicate SKUs, negative prices, and variants without options. Illegal states are never represented.

Use cases are created by injecting their dependencies:

typescript
1export const createProductUseCase =
2 (repository: ProductRepository) =>
3 async (command: CreateProductCommand): Promise<Result<Product, DomainError>> => {
4 // validate through the domain, then persist through the port
5 };

Production wires the Knex adapter; tests wire a plain fake.

Request lifecycle

A create-product request passes through a deliberately small shell:

text
1POST /v1/products
2 → authenticateUser
3 → validate Joi request schema
4 → hasStoreAccess
5 → HTTP handler
6 → map snake_case request to camelCase command
7 → call use case
8 → map DomainError to HTTP error
9 → validate response schema
10 → send response

The domain and application layers never see Express request objects, Joi schemas, or SQL rows.

Bounded contexts

ContextMain responsibility
catalogProducts, variants, options, pricing rules.
ordersOrder creation, reads, amendment, cancellation, and status transitions.
cartAdd, update, remove, and read cart items.
identityProfiles and registration through Supabase Auth.
fulfillmentDelivery information and addresses.
store-managementStores, staff, and access roles.
reviewsProduct, vendor, and customer reviews.
analyticsRead models for vendor dashboards.
mediaAvatar and product media through Cloudinary.
paymentsPaystack initialization, webhooks, callbacks, and QStash jobs.

The order aggregate owns a small state machine (pending → processing → shipped → delivered, with failure, cancellation, and refund paths). Creation and amendment share the same item builder, so stock, quantity, and price-snapshot rules cannot drift.

Testing strategy

The backend follows a testing pyramid: many fast unit tests, fewer integration tests over adapters and wiring, and a small adversarial end-to-end suite for cross-layer behavior.

The last full run on Node 22 had 434 tests across 151 suites, all passing in about 4m15s: 150 unit and 284 integrated, including 101 adversarial cases.

LayerTypeWhat it covers
shared/ + domain/UnitInvariants, money arithmetic, state transitions, boundary values.
application/Unit with fakesOrchestration, error mapping, and rejecting invalid input before persistence.
infra/ + http/IntegrationSQL correctness, camelCase ⇄ snake_case mapping, Joi schemas, route wiring.
Whole appAdversarial E2EContracts, authorization, ownership, replay/state machines, query injection.

External services stay behind ports, so unit tests use plain fakes: no Paystack, no Cloudinary, no network. Integration tests run against local Supabase and a test server.

Running the tests

bash
1cd packages/thrift-api
2supabase start
3pnpm build
4pnpm test-server # API on localhost:1027
5pnpm test # full suite

Automation uses the agent variants instead: pnpm test-server:agent on port 1037, then pnpm test:agent. Useful variants include pnpm test:agent:debug, pnpm test --grep "Catalog", pnpm coverage:agent, and pnpm typecheck:agent. The QStash-dependent payment tests also need the local QStash dev server and its signing keys.

Test conventions

Tests are independent: each seeds and tears down its own data. Imports go through the #src/... alias. The HTTP and database boundaries use snake_case; the domain uses camelCase. External-service behavior is verified through adapter tests and adversarial end-to-end cases, not by mocking the network in unit tests.

CI and coverage

The run-tests.yml workflow runs on pushes and pull requests to main and dev. It starts Supabase, builds and typechecks the API, enforces the coverage gate (65% lines, 70% functions, 75% branches, 65% statements over shared/ and domain code), starts QStash and the API on port 1027, then runs the full suite with one retry. A successful test run triggers the API production deployment workflow.

Production runs on Cloudflare Workers. The Next.js storefront is built with OpenNext, the Express API is served from its own Worker, and Postgres connects through Hyperdrive.

Known gaps: the legacy cart integration suite still shares state across cases, payment tests are registered at module scope outside the main suite wrapper, and there are no consumer contract, property-based, or mutation tests yet.

Data model

The schema is a single consolidated Supabase migration rather than a chain of incremental migrations. pnpm reset-db replays the migration and runs the seed file; pnpm docs:schema regenerates the table and ER reference from the live database.

Core tables

AreaTables
Catalogproducts, product_variants, product_options, product_option_values, variant_to_option_values, variant_price_overrides
Inventoryinventory, locations, product_availability
Commerceshopping_cart, shopping_cart_item, orders, order_items
Identity and storesprofiles, stores, store_staff, address, delivery_info
Payments and ledgertransactions, processed_webhooks, financial_accounts, ledger_entries, ledger_lines
Content and reviewspages, page_sections, featured_product_collections, product_reviews, vendor_reviews, customer_reviews

Read models include product_variant_inventory, user_wallet_balance, and product_variant_effective_price.

Schema principles

  • Money is stored as integer minor units (kobo) in the domain and as BIGINT/NUMERIC at the database boundary.
  • Aggregates protect invariants; the database enforces the rest with foreign keys, checks, triggers, and partial uniqueness.
  • Pricing combines a base price, option modifiers, and time-bound overrides into an effective price.
  • Inventory is an append-only quantity-change ledger; available stock is derived through a view.
  • Payment webhooks are recorded in processed_webhooks so retries are idempotent.
  • Ledger entries are protected from modification, and each entry is checked for balanced lines.

Conventions

  • Expected failures are DomainError values returned inside a Result; unexpected failures throw and reach the global error handler.
  • The domain never imports Express or Knex.
  • Adapters own the snake_case/camelCase mapping at the boundary.
  • Business rules live in one place; the HTTP layer stays thin.
  • Legacy code is replaced incrementally and deleted only after the replacement is wired and green.
  • Persistence-only contexts may keep snake_case end-to-end where there are no domain invariants to protect.