Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Commenting gate.ts #2635

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/system/decorators/gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,14 @@
import { isPromise } from '../promise';
import { resolveProp } from './resolver';

/**
* A decorator that gates the execution of a method or getter.
* It ensures that the decorated method is executed only once at a time
* by forcing subsequent calls to wait for the previous execution to complete.
*/
export function gate<T extends (...arg: any) => any>(resolver?: (...args: Parameters<T>) => string) {
return (target: any, key: string, descriptor: PropertyDescriptor) => {
// Stores the original method or getter function in fn variable
let fn: Function | undefined;
if (typeof descriptor.value === 'function') {
fn = descriptor.value;
Expand All @@ -12,10 +18,15 @@ export function gate<T extends (...arg: any) => any>(resolver?: (...args: Parame
}
if (fn == null) throw new Error('Not supported');

// Creates a unique gate key
const gateKey = `$gate$${key}`;

// Replaces the descriptor value with a new function
descriptor.value = function (this: any, ...args: any[]) {
// Resolves the gate key using the resolver function
const prop = resolveProp(gateKey, resolver, ...(args as Parameters<T>));

// Checks if a promise has already been created for the method
if (!Object.prototype.hasOwnProperty.call(this, prop)) {
Object.defineProperty(this, prop, {
configurable: false,
Expand All @@ -25,15 +36,21 @@ export function gate<T extends (...arg: any) => any>(resolver?: (...args: Parame
});
}

// If a promise exists, return it
let promise = this[prop];
if (promise === undefined) {
let result;
try {
// Call the original method
result = fn!.apply(this, args);

// If the result is not a promise, return it
if (result == null || !isPromise(result)) {
return result;
}

// If the result is a promise, set up .then and .catch
// handlers to clear the promise on completion
this[prop] = promise = result
.then((r: any) => {
this[prop] = undefined;
Expand All @@ -49,6 +66,7 @@ export function gate<T extends (...arg: any) => any>(resolver?: (...args: Parame
}
}

// Return the ongoing promise
return promise;
};
};
Expand Down