cache-ttl-provider.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * @description
  3. * This interface is used to provide the current time in milliseconds.
  4. * The reason it is abstracted in this way is so that the cache
  5. * implementations can be more easily tested.
  6. *
  7. * In an actual application you would not need to change the default.
  8. */
  9. export interface CacheTtlProvider {
  10. /**
  11. * @description
  12. * Returns the current timestamp in milliseconds.
  13. */
  14. getTime(): number;
  15. }
  16. /**
  17. * @description
  18. * The default implementation of the {@link CacheTtlProvider} which
  19. * simply returns the current time.
  20. */
  21. export class DefaultCacheTtlProvider implements CacheTtlProvider {
  22. /**
  23. * @description
  24. * Returns the current timestamp in milliseconds.
  25. */
  26. getTime(): number {
  27. return new Date().getTime();
  28. }
  29. }
  30. /**
  31. * @description
  32. * A testing implementation of the {@link CacheTtlProvider} which
  33. * allows the time to be set manually.
  34. */
  35. export class TestingCacheTtlProvider implements CacheTtlProvider {
  36. private time = 0;
  37. setTime(timestampInMs: number) {
  38. this.time = timestampInMs;
  39. }
  40. incrementTime(ms: number) {
  41. this.time += ms;
  42. }
  43. getTime(): number {
  44. return this.time;
  45. }
  46. }