Skip to content

Commit

Permalink
fix: allow to hooks a function without middleware (#77)
Browse files Browse the repository at this point in the history
  • Loading branch information
bertho-zero committed Apr 11, 2021
1 parent 82be08e commit 38b44c3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
10 changes: 6 additions & 4 deletions packages/hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export type MiddlewareOptions = {
/**
* Initializes a hook settings object with the given middleware.
* @param mw The list of middleware
* @param options Middleware options (params, default, props)
*/
export function middleware (mw?: Middleware[], options?: MiddlewareOptions) {
const manager = new HookManager().middleware(mw);
Expand Down Expand Up @@ -55,7 +56,8 @@ export function middleware (mw?: Middleware[], options?: MiddlewareOptions) {
* (`middleware([]).params()` etc.)
*/
export function hooks<F, T = any> (
fn: F, manager: HookManager
fn: F&(() => void),
manager?: HookManager
): WrappedFunction<F, T>;

/**
Expand All @@ -68,17 +70,17 @@ export function hooks<O> (obj: O|(new (...args: any[]) => O), hookMap: HookMap<O

/**
* Decorate a class method with hooks.
* @param _manager The hooks settings
* @param manager The hooks settings
*/
export function hooks<T = any> (
_manager?: HookOptions
manager?: HookOptions
): any;

// Fallthrough to actual implementation
export function hooks (...args: any[]) {
const [ target, _hooks ] = args;

if (typeof target === 'function' && (_hooks instanceof HookManager || Array.isArray(_hooks))) {
if (typeof target === 'function' && (_hooks instanceof HookManager || Array.isArray(_hooks) || args.length === 1)) {
return functionHooks(target, _hooks);
}

Expand Down
7 changes: 7 additions & 0 deletions packages/hooks/test/function.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ describe('functionHooks', () => {
assert.notStrictEqual(getManager(fn), null);
});

it('returns a new function, without hooks', () => {
const fn = hooks(hello);

assert.notDeepEqual(fn, hello);
assert.ok(getManager(fn) !== null);
});

it('throws an error with non function', () => {
assert.throws(() => functionHooks({}, middleware([])));
})
Expand Down

0 comments on commit 38b44c3

Please sign in to comment.