Socket
Socket
Sign inDemoInstall

@feathersjs/hooks

Package Overview
Dependencies
0
Maintainers
4
Versions
22
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.5.0-alpha.0 to 0.5.0

deno/context.ts

13

CHANGELOG.md

@@ -6,2 +6,15 @@ # Change Log

# [0.5.0](https://github.com/feathersjs/hooks/compare/v0.5.0-alpha.0...v0.5.0) (2020-06-01)
### Features
* **hooks:** Finalize default initializer functionality ([#35](https://github.com/feathersjs/hooks/issues/35)) ([d380d76](https://github.com/feathersjs/hooks/commit/d380d76891b28160c992438bfb3f28493eacddc4))
* **hooks:** Refactor .params, .props and .defaults into hooks ([#37](https://github.com/feathersjs/hooks/issues/37)) ([9b13b7d](https://github.com/feathersjs/hooks/commit/9b13b7de6b708a2152927335aae25dd320b4cfeb))
* **typescript:** Improve type indexes for stricter object and class hooks ([699f2fd](https://github.com/feathersjs/hooks/commit/699f2fd973eb72c0d7c3aefff7b230a7a8a2918a))
# [0.5.0-alpha.0](https://github.com/feathersjs/hooks/compare/v0.4.0-alpha.0...v0.5.0-alpha.0) (2020-04-05)

@@ -8,0 +21,0 @@

74

deno/base.ts
import { Middleware } from './compose.ts';
import { copyToSelf } from './utils';

@@ -8,5 +7,2 @@ export const HOOKS: string = Symbol('@feathersjs/hooks') as any;

/**
* The base hook context.
*/
export class HookContext<T = any, C = any> {

@@ -26,8 +22,7 @@ result?: T;

export type HookDefaultsInitializer = (context: HookContext) => HookContextData;
export class HookManager {
_parent?: this|null = null;
_params: string[] = [];
_middleware: Middleware[] = [];
_props: HookContextData = {};
_defaults: HookContextData|(() => HookContextData) = {};

@@ -46,2 +41,6 @@ parent (parent: this) {

getContextClass (): HookContextConstructor {
return HookContext;
}
getMiddleware (): Middleware[] {

@@ -53,66 +52,9 @@ const previous = this._parent ? this._parent.getMiddleware() : [];

collectMiddleware (self: any, _args: any[]): Middleware[] {
collectMiddleware (self: any, _args: any[]): Middleware[] {
const otherMiddleware = getMiddleware(self);
return otherMiddleware.concat(this.getMiddleware().reverse());
return otherMiddleware.concat(this.getMiddleware());
}
props (props: HookContextData) {
Object.assign(this._props, props);
return this;
}
getProps (): HookContextData {
const previous = this._parent ? this._parent.getProps() : {};
return Object.assign({}, previous, this._props);
}
params (...params: string[]) {
this._params = params;
return this;
}
getParams (): string[] {
const previous = this._parent ? this._parent.getParams() : [];
return previous.concat(this._params);
}
defaults (defaults: HookContextData|(() => HookContextData)) {
this._defaults = defaults;
return this;
}
getContextClass (Base: HookContextConstructor = HookContext): HookContextConstructor {
const ContextClass = class ContextClass extends Base {
constructor (data: any) {
super(data);
copyToSelf(this);
}
};
const params = this.getParams();
const props = this.getProps();
params.forEach((name, index) => {
Object.defineProperty(ContextClass.prototype, name, {
enumerable: true,
get () {
return this.arguments[index];
},
set (value: any) {
this.arguments[index] = value;
}
});
});
Object.assign(ContextClass.prototype, props);
return ContextClass;
}
initializeContext (self: any, args: any[], context: HookContext): HookContext {

@@ -119,0 +61,0 @@ const ctx = this._parent ? this._parent.initializeContext(self, args, context) : context;

import { functionHooks } from './function.ts';
import { setManager, HookOptions, convertOptions } from './base.ts';
import { properties } from './context';

@@ -20,3 +21,4 @@ export const hookDecorator = (managerOrMiddleware?: HookOptions) => {

descriptor.value = functionHooks(fn, manager.props({ method}));
manager._middleware.unshift(properties({ method }));
descriptor.value = functionHooks(fn, manager);

@@ -23,0 +25,0 @@ return descriptor;

@@ -5,4 +5,22 @@ import { compose, Middleware } from './compose.ts';

} from './base.ts';
import { getOriginal, copyProperties } from './utils';
export function getOriginal (fn: any): any {
return typeof fn.original === 'function' ? getOriginal(fn.original) : fn;
}
function copyProperties <F> (target: F, original: any) {
const originalProps = (Object.keys(original) as any)
.concat(Object.getOwnPropertySymbols(original));
for (const prop of originalProps) {
const propDescriptor = Object.getOwnPropertyDescriptor(original, prop);
if (!target.hasOwnProperty(prop)) {
Object.defineProperty(target, prop, propDescriptor);
}
}
return target;
}
/**

@@ -9,0 +27,0 @@ * Returns a new function that is wrapped in the given hooks.

@@ -7,2 +7,3 @@ import { functionHooks } from './function.ts';

export * as setContext from './context';
export * from './function.ts';

@@ -20,3 +21,7 @@ export * from './compose.ts';

export function middleware (mw: Middleware[]) {
/**
* Initializes a hook settings object with the given middleware.
* @param mw The list of middleware
*/
export function middleware (mw: Middleware[] = []) {
const manager = new HookManager();

@@ -27,12 +32,30 @@

// hooks(fn, hookOptions)
/**
* Returns a new function that wraps an existing async function
* with hooks.
*
* @param fn The async function to add hooks to.
* @param manager An array of middleware or hook settings
* (`middleware([]).params()` etc.)
*/
export function hooks<F, T = any> (
fn: F, manager: HookManager
): WrappedFunction<F, T>;
// hooks(object, hookMap)
export function hooks<O> (obj: O, hookMap: HookMap|Middleware[]): O;
// @hooks(hookOptions)
/**
* Add hooks to one or more methods on an object or class.
* @param obj The object to add hooks to
* @param hookMap A map of middleware settings where the
* key is the method name.
*/
export function hooks<O> (obj: O|(new (...args: any[]) => O), hookMap: HookMap<O>|Middleware[]): O;
/**
* Decorate a class method with hooks.
* @param _manager The hooks settings
*/
export function hooks<T = any> (
_manager?: HookOptions
): any;
// Fallthrough to actual implementation

@@ -39,0 +62,0 @@ export function hooks (...args: any[]) {

import { Middleware } from './compose.ts';
import { functionHooks } from './function.ts';
import { setMiddleware, convertOptions, HookOptions } from './base.ts';
import { properties } from './context';
export interface HookMap {
[key: string]: HookOptions;
export type HookMap<O = any> = {
[L in keyof O]?: HookOptions;
}

@@ -25,6 +26,8 @@

result[method] = functionHooks(fn, manager.props({ method }));
manager._middleware.unshift(properties({ method }));
result[method] = functionHooks(fn, manager);
return result;
}, obj);
};

@@ -1,1 +0,1 @@

!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.hooks=e():t.hooks=e()}(this,(function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=4)}([function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const n=r(3);e.HOOKS=Symbol("@feathersjs/hooks");class o{constructor(t={}){Object.assign(this,t)}}e.HookContext=o;class i{constructor(){this._parent=null,this._params=[],this._middleware=[],this._props={},this._defaults={}}parent(t){return this._parent=t,this}middleware(t){return this._middleware=t,this}getMiddleware(){return(this._parent?this._parent.getMiddleware():[]).concat(this._middleware)}collectMiddleware(t,e){return u(t).concat(this.getMiddleware().reverse())}props(t){return Object.assign(this._props,t),this}getProps(){const t=this._parent?this._parent.getProps():{};return Object.assign({},t,this._props)}params(...t){return this._params=t,this}getParams(){return(this._parent?this._parent.getParams():[]).concat(this._params)}defaults(t){return this._defaults=t,this}getContextClass(t=o){const e=class extends t{constructor(t){super(t),n.copyToSelf(this)}},r=this.getParams(),i=this.getProps();return r.forEach((t,r)=>{Object.defineProperty(e.prototype,t,{enumerable:!0,get(){return this.arguments[r]},set(t){this.arguments[r]=t}})}),Object.assign(e.prototype,i),e}initializeContext(t,e,r){const n=this._parent?this._parent.initializeContext(t,e,r):r;return t&&(n.self=t),n.arguments=e,n}}function s(t){return t&&t[e.HOOKS]||null}function c(t,r){const n=s(t);return t[e.HOOKS]=r.parent(n),t}function u(t){const e=s(t);return e?e.getMiddleware():[]}e.HookManager=i,e.convertOptions=function(t=[]){return Array.isArray(t)?(new i).middleware(t):t},e.getManager=s,e.setManager=c,e.getMiddleware=u,e.setMiddleware=function(t,e){return c(t,(new i).middleware(e))}},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const n=r(2),o=r(0),i=r(3);e.functionHooks=function(t,e){if("function"!=typeof t)throw new Error("Can not apply hooks to non-function");const r=o.convertOptions(e),s=function(...t){const{Context:e,original:o}=s,i=t[t.length-1]instanceof e,c=i?t.pop():new e,u=r.initializeContext(this,t,c),a=[(t,e)=>e().then(()=>i?t:t.result),...r.collectMiddleware(this,t),(t,e)=>void 0===t.result?Promise.resolve(o.apply(this,t.arguments)).then(r=>(t.result=r,e())):e()];return n.compose(a).call(this,u)};return i.copyProperties(s,t),o.setManager(s,r),Object.assign(s,{original:i.getOriginal(t),Context:r.getContextClass(),createContext:(t={})=>new s.Context(t)})}},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.compose=function(t){if(!Array.isArray(t))throw new TypeError("Middleware stack must be an array!");for(const e of t)if("function"!=typeof e)throw new TypeError("Middleware must be composed of functions!");return function(e,r){let n=-1;return function o(i){if(i<=n)return Promise.reject(new Error("next() called multiple times"));n=i;let s=t[i];i===t.length&&(s=r);if(!s)return Promise.resolve();try{return Promise.resolve(s.call(this,e,o.bind(this,i+1)))}catch(t){return Promise.reject(t)}}.call(this,0)}}},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getOriginal=function t(e){return"function"==typeof e.original?t(e.original):e},e.copyProperties=function(t,e){const r=Object.keys(e).concat(Object.getOwnPropertySymbols(e));for(const n of r){const r=Object.getOwnPropertyDescriptor(e,n);t.hasOwnProperty(n)||Object.defineProperty(t,n,r)}return t};const n=Object.prototype,o="function"==typeof n.__lookupGetter__&&"function"==typeof n.__defineGetter__&&"function"==typeof n.__defineSetter__;e.copyToSelf=function(t){for(const e in t)if(!t.hasOwnProperty(e)){const r=o?t.constructor.prototype.__lookupGetter__(e):Object.getOwnPropertyDescriptor(t,e);r&&o?(t.__defineGetter__(e,r),t.__defineSetter__(e,t.constructor.prototype.__lookupSetter__(e))):r?Object.defineProperty(t,e,r):t[e]=t[e]}}},function(t,e,r){"use strict";function n(t){for(var r in t)e.hasOwnProperty(r)||(e[r]=t[r])}Object.defineProperty(e,"__esModule",{value:!0});const o=r(1),i=r(5),s=r(6),c=r(0);n(r(1)),n(r(2)),n(r(0)),e.middleware=function(t){return(new c.HookManager).middleware(t)},e.hooks=function(...t){const[e,r]=t;return"function"==typeof e&&(r instanceof c.HookManager||Array.isArray(r))?o.functionHooks(e,r):2===t.length?i.objectHooks(e,r):s.hookDecorator(e)}},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const n=r(1),o=r(0);e.objectHooks=function(t,e){const r="function"==typeof t?t.prototype:t;return Array.isArray(e)?o.setMiddleware(r,e):Object.keys(e).reduce((t,i)=>{const s=r[i];if("function"!=typeof s)throw new Error(`Can not apply hooks. '${i}' is not a function`);const c=o.convertOptions(e[i]);return t[i]=n.functionHooks(s,c.props({method:i})),t},r)}},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const n=r(1),o=r(0);e.hookDecorator=t=>(e,r,i)=>{const s=o.convertOptions(t);if(!i)return o.setManager(e.prototype,s),e;const c=i.value;if("function"!=typeof c)throw new Error(`Can not apply hooks. '${r}' is not a function`);return i.value=n.functionHooks(c,s.props({method:r})),i}}])}));
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.hooks=t():e.hooks=t()}(this,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=4)}([function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HOOKS=Symbol("@feathersjs/hooks");class r{constructor(e={}){Object.assign(this,e)}}t.HookContext=r;class o{constructor(){this._parent=null,this._middleware=[]}parent(e){return this._parent=e,this}middleware(e){return this._middleware=e,this}getContextClass(){return r}getMiddleware(){return(this._parent?this._parent.getMiddleware():[]).concat(this._middleware)}collectMiddleware(e,t){return c(e).concat(this.getMiddleware())}initializeContext(e,t,n){const r=this._parent?this._parent.initializeContext(e,t,n):n;return e&&(r.self=e),r.arguments=t,r}}function i(e){return e&&e[t.HOOKS]||null}function s(e,n){const r=i(e);return e[t.HOOKS]=n.parent(r),e}function c(e){const t=i(e);return t?t.getMiddleware():[]}t.HookManager=o,t.convertOptions=function(e=[]){return Array.isArray(e)?(new o).middleware(e):e},t.getManager=i,t.setManager=s,t.getMiddleware=c,t.setMiddleware=function(e,t){return s(e,(new o).middleware(t))}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=n(3),o=n(0);function i(e){return"function"==typeof e.original?i(e.original):e}t.getOriginal=i,t.functionHooks=function(e,t){if("function"!=typeof e)throw new Error("Can not apply hooks to non-function");const n=o.convertOptions(t),s=function(...e){const{Context:t,original:o}=s,i=e[e.length-1]instanceof t,c=i?e.pop():new t,u=n.initializeContext(this,e,c),a=[(e,t)=>t().then(()=>i?e:e.result),...n.collectMiddleware(this,e),(e,t)=>void 0===e.result?Promise.resolve(o.apply(this,e.arguments)).then(n=>(e.result=n,t())):t()];return r.compose(a).call(this,u)};return function(e,t){const n=Object.keys(t).concat(Object.getOwnPropertySymbols(t));for(const r of n){const n=Object.getOwnPropertyDescriptor(t,r);e.hasOwnProperty(r)||Object.defineProperty(e,r,n)}}(s,e),o.setManager(s,n),Object.assign(s,{original:i(e),Context:n.getContextClass(),createContext:(e={})=>new s.Context(e)})}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.params=function(...e){const t=e.reduce((e,t,n)=>(e[t]={enumerable:!0,get(){return this.arguments[n]},set(e){this.arguments[n]=e}},e),{});return async function(e,n){Object.defineProperties(e,t),await n()}},t.properties=function(e){return async function(t,n){Object.assign(t,e),await n()}},t.defaults=function(e){return async function(t,n){const r=await e(t);for(const e of Object.keys(r))void 0===t[e]&&(t[e]=r[e]);await n()}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.compose=function(e){if(!Array.isArray(e))throw new TypeError("Middleware stack must be an array!");for(const t of e)if("function"!=typeof t)throw new TypeError("Middleware must be composed of functions!");return function(t,n){let r=-1;return function o(i){if(i<=r)return Promise.reject(new Error("next() called multiple times"));r=i;let s=e[i];i===e.length&&(s=n);if(!s)return Promise.resolve();try{return Promise.resolve(s.call(this,t,o.bind(this,i+1)))}catch(e){return Promise.reject(e)}}.call(this,0)}}},function(e,t,n){"use strict";function r(e){for(var n in e)t.hasOwnProperty(n)||(t[n]=e[n])}var o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=n(1),s=n(5),c=n(6),u=n(0);t.setContext=o(n(2)),r(n(1)),r(n(3)),r(n(0)),t.middleware=function(e=[]){return(new u.HookManager).middleware(e)},t.hooks=function(...e){const[t,n]=e;return"function"==typeof t&&(n instanceof u.HookManager||Array.isArray(n))?i.functionHooks(t,n):2===e.length?s.objectHooks(t,n):c.hookDecorator(t)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=n(1),o=n(0),i=n(2);t.objectHooks=function(e,t){const n="function"==typeof e?e.prototype:e;return Array.isArray(t)?o.setMiddleware(n,t):Object.keys(t).reduce((e,s)=>{const c=n[s];if("function"!=typeof c)throw new Error(`Can not apply hooks. '${s}' is not a function`);const u=o.convertOptions(t[s]);return u._middleware.unshift(i.properties({method:s})),e[s]=r.functionHooks(c,u),e},n)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=n(1),o=n(0),i=n(2);t.hookDecorator=e=>(t,n,s)=>{const c=o.convertOptions(e);if(!s)return o.setManager(t.prototype,c),t;const u=s.value;if("function"!=typeof u)throw new Error(`Can not apply hooks. '${n}' is not a function`);return c._middleware.unshift(i.properties({method:n})),s.value=r.functionHooks(u,c),s}}])}));

@@ -6,5 +6,2 @@ import { Middleware } from './compose';

};
/**
* The base hook context.
*/
export declare class HookContext<T = any, C = any> {

@@ -21,18 +18,11 @@ result?: T;

}) => HookContext;
export declare type HookDefaultsInitializer = (context: HookContext) => HookContextData;
export declare class HookManager {
_parent?: this | null;
_params: string[];
_middleware: Middleware[];
_props: HookContextData;
_defaults: HookContextData | (() => HookContextData);
parent(parent: this): this;
middleware(middleware: Middleware[]): this;
getContextClass(): HookContextConstructor;
getMiddleware(): Middleware[];
collectMiddleware(self: any, _args: any[]): Middleware[];
props(props: HookContextData): this;
getProps(): HookContextData;
params(...params: string[]): this;
getParams(): string[];
defaults(defaults: HookContextData | (() => HookContextData)): this;
getContextClass(Base?: HookContextConstructor): HookContextConstructor;
initializeContext(self: any, args: any[], context: HookContext): HookContext;

@@ -39,0 +29,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./utils");
exports.HOOKS = Symbol('@feathersjs/hooks');
/**
* The base hook context.
*/
class HookContext {

@@ -17,6 +13,3 @@ constructor(data = {}) {

this._parent = null;
this._params = [];
this._middleware = [];
this._props = {};
this._defaults = {};
}

@@ -31,2 +24,5 @@ parent(parent) {

}
getContextClass() {
return HookContext;
}
getMiddleware() {

@@ -38,47 +34,4 @@ const previous = this._parent ? this._parent.getMiddleware() : [];

const otherMiddleware = getMiddleware(self);
return otherMiddleware.concat(this.getMiddleware().reverse());
return otherMiddleware.concat(this.getMiddleware());
}
props(props) {
Object.assign(this._props, props);
return this;
}
getProps() {
const previous = this._parent ? this._parent.getProps() : {};
return Object.assign({}, previous, this._props);
}
params(...params) {
this._params = params;
return this;
}
getParams() {
const previous = this._parent ? this._parent.getParams() : [];
return previous.concat(this._params);
}
defaults(defaults) {
this._defaults = defaults;
return this;
}
getContextClass(Base = HookContext) {
const ContextClass = class ContextClass extends Base {
constructor(data) {
super(data);
utils_1.copyToSelf(this);
}
};
const params = this.getParams();
const props = this.getProps();
params.forEach((name, index) => {
Object.defineProperty(ContextClass.prototype, name, {
enumerable: true,
get() {
return this.arguments[index];
},
set(value) {
this.arguments[index] = value;
}
});
});
Object.assign(ContextClass.prototype, props);
return ContextClass;
}
initializeContext(self, args, context) {

@@ -85,0 +38,0 @@ const ctx = this._parent ? this._parent.initializeContext(self, args, context) : context;

@@ -5,2 +5,3 @@ "use strict";

const base_1 = require("./base");
const context_1 = require("./context");
exports.hookDecorator = (managerOrMiddleware) => {

@@ -17,3 +18,4 @@ const wrapper = (_target, method, descriptor) => {

}
descriptor.value = function_1.functionHooks(fn, manager.props({ method }));
manager._middleware.unshift(context_1.properties({ method }));
descriptor.value = function_1.functionHooks(fn, manager);
return descriptor;

@@ -20,0 +22,0 @@ };

import { HookOptions } from './base';
export declare function getOriginal(fn: any): any;
/**

@@ -3,0 +4,0 @@ * Returns a new function that is wrapped in the given hooks.

@@ -5,3 +5,17 @@ "use strict";

const base_1 = require("./base");
const utils_1 = require("./utils");
function getOriginal(fn) {
return typeof fn.original === 'function' ? getOriginal(fn.original) : fn;
}
exports.getOriginal = getOriginal;
function copyProperties(target, original) {
const originalProps = Object.keys(original)
.concat(Object.getOwnPropertySymbols(original));
for (const prop of originalProps) {
const propDescriptor = Object.getOwnPropertyDescriptor(original, prop);
if (!target.hasOwnProperty(prop)) {
Object.defineProperty(target, prop, propDescriptor);
}
}
return target;
}
/**

@@ -49,6 +63,6 @@ * Returns a new function that is wrapped in the given hooks.

};
utils_1.copyProperties(wrapper, fn);
copyProperties(wrapper, fn);
base_1.setManager(wrapper, manager);
return Object.assign(wrapper, {
original: utils_1.getOriginal(fn),
original: getOriginal(fn),
Context: manager.getContextClass(),

@@ -55,0 +69,0 @@ createContext: (data = {}) => {

import { Middleware } from './compose';
import { HookMap } from './object';
import { HookManager, HookContextData, HookContext, HookContextConstructor, HookOptions } from './base';
export * as setContext from './context';
export * from './function';

@@ -13,5 +14,27 @@ export * from './compose';

export declare type WrappedFunction<F, T> = F & ((...rest: any[]) => Promise<T> | Promise<HookContext>) & WrapperAddon<F>;
export declare function middleware(mw: Middleware[]): HookManager;
/**
* Initializes a hook settings object with the given middleware.
* @param mw The list of middleware
*/
export declare function middleware(mw?: Middleware[]): HookManager;
/**
* Returns a new function that wraps an existing async function
* with hooks.
*
* @param fn The async function to add hooks to.
* @param manager An array of middleware or hook settings
* (`middleware([]).params()` etc.)
*/
export declare function hooks<F, T = any>(fn: F, manager: HookManager): WrappedFunction<F, T>;
export declare function hooks<O>(obj: O, hookMap: HookMap | Middleware[]): O;
/**
* Add hooks to one or more methods on an object or class.
* @param obj The object to add hooks to
* @param hookMap A map of middleware settings where the
* key is the method name.
*/
export declare function hooks<O>(obj: O | (new (...args: any[]) => O), hookMap: HookMap<O> | Middleware[]): O;
/**
* Decorate a class method with hooks.
* @param _manager The hooks settings
*/
export declare function hooks<T = any>(_manager?: HookOptions): any;

@@ -5,2 +5,9 @@ "use strict";

}
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -11,6 +18,11 @@ const function_1 = require("./function");

const base_1 = require("./base");
exports.setContext = __importStar(require("./context"));
__export(require("./function"));
__export(require("./compose"));
__export(require("./base"));
function middleware(mw) {
/**
* Initializes a hook settings object with the given middleware.
* @param mw The list of middleware
*/
function middleware(mw = []) {
const manager = new base_1.HookManager();

@@ -17,0 +29,0 @@ return manager.middleware(mw);

import { Middleware } from './compose';
import { HookOptions } from './base';
export interface HookMap {
[key: string]: HookOptions;
}
export declare type HookMap<O = any> = {
[L in keyof O]?: HookOptions;
};
export declare function objectHooks(_obj: any, hooks: HookMap | Middleware[]): any;

@@ -5,2 +5,3 @@ "use strict";

const base_1 = require("./base");
const context_1 = require("./context");
function objectHooks(_obj, hooks) {

@@ -17,3 +18,4 @@ const obj = typeof _obj === 'function' ? _obj.prototype : _obj;

const manager = base_1.convertOptions(hooks[method]);
result[method] = function_1.functionHooks(fn, manager.props({ method }));
manager._middleware.unshift(context_1.properties({ method }));
result[method] = function_1.functionHooks(fn, manager);
return result;

@@ -20,0 +22,0 @@ }, obj);

{
"name": "@feathersjs/hooks",
"version": "0.5.0-alpha.0",
"version": "0.5.0",
"description": "Async middleware for JavaScript and TypeScript",

@@ -58,3 +58,3 @@ "homepage": "https://feathersjs.com",

},
"gitHead": "b31bf55f1cd59620dcb4f3a41b4141557841c551"
"gitHead": "740a8591176e0f66eb3c8ac1c6f5ac07172b4f88"
}
import { Middleware } from './compose';
import { copyToSelf } from './utils';

@@ -8,5 +7,2 @@ export const HOOKS: string = Symbol('@feathersjs/hooks') as any;

/**
* The base hook context.
*/
export class HookContext<T = any, C = any> {

@@ -26,8 +22,7 @@ result?: T;

export type HookDefaultsInitializer = (context: HookContext) => HookContextData;
export class HookManager {
_parent?: this|null = null;
_params: string[] = [];
_middleware: Middleware[] = [];
_props: HookContextData = {};
_defaults: HookContextData|(() => HookContextData) = {};

@@ -46,2 +41,6 @@ parent (parent: this) {

getContextClass (): HookContextConstructor {
return HookContext;
}
getMiddleware (): Middleware[] {

@@ -53,66 +52,9 @@ const previous = this._parent ? this._parent.getMiddleware() : [];

collectMiddleware (self: any, _args: any[]): Middleware[] {
collectMiddleware (self: any, _args: any[]): Middleware[] {
const otherMiddleware = getMiddleware(self);
return otherMiddleware.concat(this.getMiddleware().reverse());
return otherMiddleware.concat(this.getMiddleware());
}
props (props: HookContextData) {
Object.assign(this._props, props);
return this;
}
getProps (): HookContextData {
const previous = this._parent ? this._parent.getProps() : {};
return Object.assign({}, previous, this._props);
}
params (...params: string[]) {
this._params = params;
return this;
}
getParams (): string[] {
const previous = this._parent ? this._parent.getParams() : [];
return previous.concat(this._params);
}
defaults (defaults: HookContextData|(() => HookContextData)) {
this._defaults = defaults;
return this;
}
getContextClass (Base: HookContextConstructor = HookContext): HookContextConstructor {
const ContextClass = class ContextClass extends Base {
constructor (data: any) {
super(data);
copyToSelf(this);
}
};
const params = this.getParams();
const props = this.getProps();
params.forEach((name, index) => {
Object.defineProperty(ContextClass.prototype, name, {
enumerable: true,
get () {
return this.arguments[index];
},
set (value: any) {
this.arguments[index] = value;
}
});
});
Object.assign(ContextClass.prototype, props);
return ContextClass;
}
initializeContext (self: any, args: any[], context: HookContext): HookContext {

@@ -119,0 +61,0 @@ const ctx = this._parent ? this._parent.initializeContext(self, args, context) : context;

import { functionHooks } from './function';
import { setManager, HookOptions, convertOptions } from './base';
import { properties } from './context';

@@ -20,3 +21,4 @@ export const hookDecorator = (managerOrMiddleware?: HookOptions) => {

descriptor.value = functionHooks(fn, manager.props({ method}));
manager._middleware.unshift(properties({ method }));
descriptor.value = functionHooks(fn, manager);

@@ -23,0 +25,0 @@ return descriptor;

@@ -5,4 +5,22 @@ import { compose, Middleware } from './compose';

} from './base';
import { getOriginal, copyProperties } from './utils';
export function getOriginal (fn: any): any {
return typeof fn.original === 'function' ? getOriginal(fn.original) : fn;
}
function copyProperties <F> (target: F, original: any) {
const originalProps = (Object.keys(original) as any)
.concat(Object.getOwnPropertySymbols(original));
for (const prop of originalProps) {
const propDescriptor = Object.getOwnPropertyDescriptor(original, prop);
if (!target.hasOwnProperty(prop)) {
Object.defineProperty(target, prop, propDescriptor);
}
}
return target;
}
/**

@@ -9,0 +27,0 @@ * Returns a new function that is wrapped in the given hooks.

@@ -7,2 +7,3 @@ import { functionHooks } from './function';

export * as setContext from './context';
export * from './function';

@@ -20,3 +21,7 @@ export * from './compose';

export function middleware (mw: Middleware[]) {
/**
* Initializes a hook settings object with the given middleware.
* @param mw The list of middleware
*/
export function middleware (mw: Middleware[] = []) {
const manager = new HookManager();

@@ -27,12 +32,30 @@

// hooks(fn, hookOptions)
/**
* Returns a new function that wraps an existing async function
* with hooks.
*
* @param fn The async function to add hooks to.
* @param manager An array of middleware or hook settings
* (`middleware([]).params()` etc.)
*/
export function hooks<F, T = any> (
fn: F, manager: HookManager
): WrappedFunction<F, T>;
// hooks(object, hookMap)
export function hooks<O> (obj: O, hookMap: HookMap|Middleware[]): O;
// @hooks(hookOptions)
/**
* Add hooks to one or more methods on an object or class.
* @param obj The object to add hooks to
* @param hookMap A map of middleware settings where the
* key is the method name.
*/
export function hooks<O> (obj: O|(new (...args: any[]) => O), hookMap: HookMap<O>|Middleware[]): O;
/**
* Decorate a class method with hooks.
* @param _manager The hooks settings
*/
export function hooks<T = any> (
_manager?: HookOptions
): any;
// Fallthrough to actual implementation

@@ -39,0 +62,0 @@ export function hooks (...args: any[]) {

import { Middleware } from './compose';
import { functionHooks } from './function';
import { setMiddleware, convertOptions, HookOptions } from './base';
import { properties } from './context';
export interface HookMap {
[key: string]: HookOptions;
export type HookMap<O = any> = {
[L in keyof O]?: HookOptions;
}

@@ -25,6 +26,8 @@

result[method] = functionHooks(fn, manager.props({ method }));
manager._middleware.unshift(properties({ method }));
result[method] = functionHooks(fn, manager);
return result;
}, obj);
};

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc