Skip to content

Commit

Permalink
refactor(backend): use Reflet for autobind deco (#14482)
Browse files Browse the repository at this point in the history
Using Reflect.defineProperty instead of Object.defineProperty
gives a more consistent behavior with the rest of the modern
JavaScript features.
  • Loading branch information
zzau13 committed Sep 15, 2024
1 parent 366b79e commit 07f26bc
Showing 1 changed file with 7 additions and 14 deletions.
21 changes: 7 additions & 14 deletions packages/backend/src/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
* The getter will return a .bind version of the function
* and memoize the result against a symbol on the instance
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function bindThis(target: any, key: string, descriptor: any) {
let fn = descriptor.value;
const fn = descriptor.value;

if (typeof fn !== 'function') {
throw new TypeError(`@bindThis decorator can only be applied to methods not: ${typeof fn}`);
Expand All @@ -21,26 +22,18 @@ export function bindThis(target: any, key: string, descriptor: any) {
configurable: true,
get() {
// eslint-disable-next-line no-prototype-builtins
if (this === target.prototype || this.hasOwnProperty(key) ||
typeof fn !== 'function') {
if (this === target.prototype || this.hasOwnProperty(key)) {
return fn;
}

const boundFn = fn.bind(this);
Object.defineProperty(this, key, {
Reflect.defineProperty(this, key, {
value: boundFn,
configurable: true,
get() {
return boundFn;
},
set(value) {
fn = value;
delete this[key];
},
writable: true,
});

return boundFn;
},
set(value: any) {
fn = value;
},
};
}

0 comments on commit 07f26bc

Please sign in to comment.