Skip to content

Commit

Permalink
feat: delay() api
Browse files Browse the repository at this point in the history
  • Loading branch information
charlypoly committed Feb 2, 2023
1 parent dcf11fd commit ca35544
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 5 deletions.
15 changes: 15 additions & 0 deletions .changeset/clever-cheetahs-compete.md
Original file line number Diff line number Diff line change
@@ -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
```
48 changes: 43 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ export interface DeferRetFn<
(...args: Parameters<F>): ReturnType<F>;
__fn: F;
await: DeferAwaitRetFn<F>;
/**
* @deprecated use `delay(deferFn)` instead
*/
delayed: (...args: DeferRetFnParameters<F>) => ReturnType<F>;
}
export interface DeferScheduledFn<F extends (...args: never) => Promise<any>>
Expand Down Expand Up @@ -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
Expand All @@ -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 =
<F extends (...args: any | undefined) => Promise<any>>(
deferFn: DeferRetFn<F>,
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()

0 comments on commit ca35544

Please sign in to comment.