Skip to content

Commit 5c95ad3

Browse files
authored
Commenting gate.ts
While reading the codebase, I was briefly confused by the gate decorator. For a second, I thought `gate to what?` ![](https://media2.giphy.com/media/KcJO5G7N7nsxe9nRku/giphy.gif?cid=ecf05e476typvmnukv78gz55o21rcvlm025dw6w3m0djk5sw) I'm hoping these comments will help others dive through the codebase as well 🙂
1 parent 640d3f6 commit 5c95ad3

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/system/decorators/gate.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,14 @@
22
import { isPromise } from '../promise';
33
import { resolveProp } from './resolver';
44

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

21+
// Creates a unique gate key
1522
const gateKey = `$gate$${key}`;
1623

24+
// Replaces the descriptor value with a new function
1725
descriptor.value = function (this: any, ...args: any[]) {
26+
// Resolves the gate key using the resolver function
1827
const prop = resolveProp(gateKey, resolver, ...(args as Parameters<T>));
28+
29+
// Checks if a promise has already been created for the method
1930
if (!Object.prototype.hasOwnProperty.call(this, prop)) {
2031
Object.defineProperty(this, prop, {
2132
configurable: false,
@@ -25,15 +36,21 @@ export function gate<T extends (...arg: any) => any>(resolver?: (...args: Parame
2536
});
2637
}
2738

39+
// If a promise exists, return it
2840
let promise = this[prop];
2941
if (promise === undefined) {
3042
let result;
3143
try {
44+
// Call the original method
3245
result = fn!.apply(this, args);
46+
47+
// If the result is not a promise, return it
3348
if (result == null || !isPromise(result)) {
3449
return result;
3550
}
3651

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

69+
// Return the ongoing promise
5270
return promise;
5371
};
5472
};

0 commit comments

Comments
 (0)