Patterns
The patterns the packages share. Following them in application code keeps a service testable and movable between runtimes.
The packages share a small set of patterns. Following them in application code keeps a service testable and movable between runtimes.
Ports and adapters
Section titled “Ports and adapters”A package asks for the methods it calls, such as { limit({ key }) } or { match, put }, never
for a vendor’s type. A platform binding, an in-memory implementation and a test double are all
adapters for the same port. Everything vendor-specific lives in
@edgetime/cloudflare; the other packages name no platform.
Composition root
Section titled “Composition root”Routes live in a module with no platform imports and read their dependencies from env and the
context. One entry file per runtime builds those dependencies. The repository’s examples do it
from Cloudflare bindings in one and from in-process implementations in the other, around the same
routes. See Deploy on Workers.
Dependencies on demand
Section titled “Dependencies on demand”provide() registers factories for per-request values and perEnv() memoizes per-environment
ones. Handlers read them with c.get() and never construct them, so a test swaps a factory
instead of a handler.
Middleware as composition
Section titled “Middleware as composition”Cross-cutting behaviour is a function around next(). compose() joins middleware into reusable
stacks, mount() joins routers and extend() installs a packaged feature.
Configured factories
Section titled “Configured factories”Anything with settings is made by a function that validates them once and returns a closure:
createJwtVerifier(), createSessionCodec(), createLogger(). A bad setting stops start-up
instead of failing requests.
Errors at the boundary, results inside
Section titled “Errors at the boundary, results inside”A handler throws an HttpError and one error handler renders it. Operations whose failure is an
expected outcome return a value instead: unseal() returns undefined, and verifyTurnstile()
returns a result with a reason.
Optional steps as data
Section titled “Optional steps as data”Redundancy and other per-deployment behaviour is switched by a flag in a list of steps
(flag(...) && step), not by branching through the code.
import { flag } from '@edgetime/config';import { firstAvailable, writeAll } from '@edgetime/resilience';
const replica = flag(env.REPLICA_ENABLED) ? env.FILES_REPLICA : undefined;
await writeAll([() => primary.put(key, bytes), replica && (() => replica.put(key, bytes))]);const object = await firstAvailable([() => primary.get(key), replica && (() => replica.get(key))]);No hidden state
Section titled “No hidden state”Nothing request-scoped lives at module level, and imports have no side effects, so every entry point tree-shakes.