Skip to content

Commit

Permalink
fix: Use Symbol.for to register a single instance of all hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
daffl committed Feb 25, 2024
1 parent 05bde46 commit a2d3aef
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions main/hooks/src/base.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { AsyncMiddleware } from './compose.ts';
import { copyProperties } from './utils.ts';

export const HOOKS: string = Symbol('@feathersjs/hooks') as any;
export const HOOKS: string = Symbol.for('@feathersjs/hooks') as any;

export type HookContextData = { [key: string]: any };

Expand Down Expand Up @@ -46,7 +46,7 @@ export type HookContextConstructor = new (data?: {
export type HookDefaultsInitializer = (
self?: any,
args?: any[],
context?: HookContext,
context?: HookContext
) => HookContextData;

export class HookManager {
Expand Down Expand Up @@ -134,9 +134,12 @@ export class HookManager {
getDefaults(
self: any,
args: any[],
context: HookContext,
context: HookContext
): HookContextData | null {
const defaults = typeof this._defaults === 'function' ? this._defaults(self, args, context) : null;
const defaults =
typeof this._defaults === 'function'
? this._defaults(self, args, context)
: null;
const previous = this._parent?.getDefaults(self, args, context);

if (previous && defaults) {
Expand All @@ -147,7 +150,7 @@ export class HookManager {
}

getContextClass(
Base: HookContextConstructor = BaseHookContext,
Base: HookContextConstructor = BaseHookContext
): HookContextConstructor {
const ContextClass = class ContextClass extends Base {
constructor(data: any) {
Expand All @@ -161,7 +164,7 @@ export class HookManager {
params.forEach((name, index) => {
if (props?.[name] !== undefined) {
throw new Error(
`Hooks can not have a property and param named '${name}'. Use .defaults instead.`,
`Hooks can not have a property and param named '${name}'. Use .defaults instead.`
);
}

Expand All @@ -172,7 +175,7 @@ export class HookManager {
},
set(value: any) {
this.arguments[index] = value;
},
}
});
});
}
Expand All @@ -185,7 +188,9 @@ export class HookManager {
}

initializeContext(self: any, args: any[], context: HookContext): HookContext {
const ctx = this._parent ? this._parent.initializeContext(self, args, context) : context;
const ctx = this._parent
? this._parent.initializeContext(self, args, context)
: context;
const defaults = this.getDefaults(self, args, ctx);

if (self) {
Expand Down Expand Up @@ -213,7 +218,9 @@ export function convertOptions(options: HookOptions = null) {
return new HookManager();
}

return Array.isArray(options) ? new HookManager().middleware(options) : options;
return Array.isArray(options)
? new HookManager().middleware(options)
: options;
}

export function getManager(target: any): HookManager | null {
Expand Down

0 comments on commit a2d3aef

Please sign in to comment.