From ca35544849cc76cff8c4038ce30eb90a293af1e0 Mon Sep 17 00:00:00 2001 From: Charly POLY Date: Thu, 2 Feb 2023 16:29:04 +0100 Subject: [PATCH] feat: `delay()` api --- .changeset/clever-cheetahs-compete.md | 15 +++++++++ src/index.ts | 48 ++++++++++++++++++++++++--- 2 files changed, 58 insertions(+), 5 deletions(-) create mode 100644 .changeset/clever-cheetahs-compete.md diff --git a/.changeset/clever-cheetahs-compete.md b/.changeset/clever-cheetahs-compete.md new file mode 100644 index 00000000..70d94f6a --- /dev/null +++ b/.changeset/clever-cheetahs-compete.md @@ -0,0 +1,15 @@ +--- +"@defer.run/client": minor +--- + +Introduce a new API to delay an execution: + +```ts +import { delay } from "@defer.run/client" +import { helloWorld } from '../defer/helloWorld'; + +// create a delayed execution +const delayedHelloWorld = delay(helloWorld, '1h') + +delayedHelloWorld() // background execution in 1 hour +``` diff --git a/src/index.ts b/src/index.ts index fbcd1986..8f41fb83 100644 --- a/src/index.ts +++ b/src/index.ts @@ -57,6 +57,9 @@ export interface DeferRetFn< (...args: Parameters): ReturnType; __fn: F; await: DeferAwaitRetFn; + /** + * @deprecated use `delay(deferFn)` instead + */ delayed: (...args: DeferRetFnParameters) => ReturnType; } export interface DeferScheduledFn Promise> @@ -170,13 +173,13 @@ defer.schedule = (fn, schedule) => { // }); // }; -async function myFunction() { - return 1; -} +// const importContactsD = defer(importContacts); -defer.schedule(myFunction, "every day"); +// async function myFunction() { +// return 1; +// } -// const importContactsD = defer(importContacts); +// defer.schedule(myFunction, "every day"); // async function test() { // await importContactsD("1", []); // fire and forget @@ -185,3 +188,38 @@ defer.schedule(myFunction, "every day"); // await importContactsD.delayed("1", [], { delay: "2 days" }); // scheduled // } + +/** + * Delay the execution of a background function + * @constructor + * @param {Function} deferFn - A background function (`defer(...)` result) + * @param {string|Date} delay - The delay (ex: "1h" or a Date object) + * @returns Function + */ +export const delay = + Promise>( + deferFn: DeferRetFn, + delay: DelayString | Date + ): (() => F) => + (...args) => { + const fn = deferFn.__fn; + if (debug) { + console.log(`[defer.run][${fn.name}] invoked.`); + } + if (token && fetcher) { + return executeBackgroundFunction(fn.name, args, fetcher, debug, { + delay, + }); + } else { + if (debug) { + console.log(`[defer.run][${fn.name}] defer ignore, no token found.`); + } + // try to serialize arguments for develpment warning purposes + serializeBackgroundFunctionArguments(fn.name, args); + // FIX: do better + return fn(...(args as any)) as any; + } + }; + +// const delayed = delay(importContactsD, '1h') +// delayed()