From 5874cb901b1bb381c9d13ec2ae831e528723335f Mon Sep 17 00:00:00 2001 From: Thom Werring Date: Sat, 23 Mar 2024 15:03:53 +0100 Subject: [PATCH] Added date faker --- src/main.ts | 6 +++++- src/utils/fake-date.ts | 32 ++++++++++++++++++++++++++++++++ src/{ => utils}/openApi.ts | 0 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 src/utils/fake-date.ts rename src/{ => utils}/openApi.ts (100%) diff --git a/src/main.ts b/src/main.ts index c1b785a..cfce60b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,6 +1,9 @@ import { NestFactory } from '@nestjs/core'; import { AppModule } from '@/app.module'; -import { openApi } from '@/openApi'; +import { openApi } from '@/utils/openApi'; +import { setDate } from '@/utils/fake-date'; + +setDate('2023-02-14 14:00:00 UTC'); async function bootstrap() { const app = await NestFactory.create(AppModule); @@ -9,4 +12,5 @@ async function bootstrap() { await app.listen(3000); } + bootstrap(); diff --git a/src/utils/fake-date.ts b/src/utils/fake-date.ts new file mode 100644 index 0000000..96bffa5 --- /dev/null +++ b/src/utils/fake-date.ts @@ -0,0 +1,32 @@ +// Save an instance of the original Date object +const ODate = Date; + +export function setDate(date: string) { + console.warn(`Time mocking has been set to ${date}`); + + Date = new Proxy(Date, { + construct( + Target: DateConstructor, + argArray: Parameters, + ): Date { + if (argArray.length === 0) { + return new Target(date); + } + + return new Target(...argArray); + }, + get(Target, prop) { + if (prop === 'now') { + return () => new Target(date).valueOf(); + } + + return Reflect.get(Target, prop); + }, + }); +} + +export function resetDate() { + console.warn(`Time mocking is now disabled`); + + Date = ODate; +} diff --git a/src/openApi.ts b/src/utils/openApi.ts similarity index 100% rename from src/openApi.ts rename to src/utils/openApi.ts