Time abstraction for NestJS
In most applications, time is everywhere:
timestamps
expiration logic
domain rules
logging
validations
comparisons
But calling new Date() directly inside your business logic makes your system:
new Date()
Hard to test
Non-deterministic
Infrastructure-coupled
Difficult to reason about
@nestjstools/clock solves this by introducing a clean abstraction over time.
@nestjstools/clock
Instead of:
You write:
And now:
You can inject time
You can freeze time in tests
You remove infrastructure concerns from your domain layer
Direct system time usage:
Creates:
Hidden side effects
Hard-to-test services
Unpredictable unit tests
Tight coupling to system clock
Time is infrastructure — it should be abstracted.
Clock introduces a simple interface:
This allows you to:
Inject system time
Replace time in tests
Last updated 3 months ago
Was this helpful?
const now = new Date();
const now = this.clock.now();
if (new Date() > expirationDate) { ... }
interface IClock { now(): Date today(): CalendarDate }