Lesson 5 of 7 · 2 min read
Patterns for recurring notification problems
Use a pattern when it solves a concrete coordination or variation problem. Follow the course notification from module construction to events and provider calls.
Use a module for a public surface
Export createReminderWorker and keep queue payload parsing and private helpers inside the module. Imports give consumers bindings to exports, while an exported mutable object can still be changed through a shared reference. Keep learner-specific state in job data or explicitly scoped instances. A module-level client may be a useful process-local default, but workers in different processes will have their own. Verify that two job runs cannot read each other’s state.
Choose construction in a factory
A factory can take a validated channel config and return an email or in-app adapter. Centralizing construction keeps credentials and provider SDK setup out of the worker. A strategy provides the interchangeable behavior the worker calls after construction. A single adapter passed directly at startup is simpler when channel never varies. If selection becomes dynamic, test supported and unsupported values and ensure new channel registration stays at the wiring boundary.
Use observers for events with defined delivery
A local observer can update metrics after a notification has been accepted. Give subscribers a cleanup path and decide what happens if a listener throws. Node’s EventEmitter calls listeners synchronously, so a slow listener can extend job latency. A local emitter does not carry a durable obligation across process restarts. If audit or downstream delivery must survive a crash, design a persisted event, retry policy and consumer deduplication. Test unsubscription and event handling after a failed provider call.
Wrap delivery without changing its promises
A decorator can measure send duration while forwarding the same input and result. A logging wrapper may accidentally throw after a provider accepted the message, leaving the caller uncertain and risking duplicates on retry. Define which telemetry failures may affect the job. A retry wrapper also needs deadlines, eligible errors and the same idempotency key across attempts. Reserve JavaScript Proxy for cases that need interception of object operations. A small explicit function is easier to inspect for one method and avoids surprises with receiver-sensitive private fields.
Name the problem first. Keep construction, observation and wrapping only where their boundaries help explain the service’s behavior.
function makeDeliveryChannel(kind, factories) {
if (!Object.hasOwn(factories, kind)) {
throw new Error('Unsupported delivery channel');
}
return factories[kind]();
}