Skip to content
generated from journy-io/package

๐Ÿ• Consume time as a service

License

Notifications You must be signed in to change notification settings

journy-io/clock

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

11 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

journy.io

Clock

npm npm downloads

Consume time as a service.

๐Ÿ’พ Installation

You can use your package manager (npm or yarn) to install:

npm install --save @journyio/clock

or

yarn add @journyio/clock

This package depends on moment/luxon. If you already have another datetime library installed in your project, we advise you to fork this package.

We don't recommend consuming this package in plain JavaScript (to be able to use interfaces).

๐Ÿ”Œ Getting started

First, read this blogpost to understand the reasoning behind this approach.

Let's say we have a class that creates a user:

import { DateTime } from "luxon";
import { Clock } from "@journyio/clock";

class User {
  constructor(/* ... */ private readonly createdAt: DateTime) {}

  getCreatedAt() {
    return this.createdAt;
  }
}

class UserService {
  constructor(private readonly clock: Clock) {}

  create(/* ... */): User {
    return new User(
      /* ... */
      this.clock.getUTCTime()
    );
  }
}

In our tests we can use ClockFixed to control the current time:

import { ClockFixed } from "@journyio/clock";

const now = DateTime.utc();
const clock = new ClockFixed(now);
const userService = new UserService(clock);
const user = userService.create(/* ... */);

expect(user.getCreatedAt()).toEqual(now);

In our normal code we can use ClockSystem:

import { ClockSystem } from "@journyio/clock";

const userService = new UserService(new ClockSystem());

By depending on Clock we can consume time as a service (so that we're in control of time). Normally we would need to rely on magic or use setTimeout to test code that uses the current time.

๐Ÿ’ฏ Tests

To run the tests:

npm run test