Skip to content

Instantly share code, notes, and snippets.

@Ivannnnn
Created May 29, 2020 10:17
Show Gist options
  • Save Ivannnnn/cc698b67371d41fc3f6cfabeb8ed48cc to your computer and use it in GitHub Desktop.
Save Ivannnnn/cc698b67371d41fc3f6cfabeb8ed48cc to your computer and use it in GitHub Desktop.
const blockOne = (funcName) => {
if (funcName === 'one') {
return false
}
}
const emitEvent = (funcName) => {
console.log('[event] ' + funcName)
}
const methods = withMiddleware([blockOne, emitEvent], {
one: () => console.log('one'),
two: () => console.log('two'),
})
methods.one()
methods.two()
/* console.log
[event] two
two
*/
const withMiddleware = (middleware, methods) => {
return new Proxy(methods, {
get: (_, methodName) => (...args) => {
if (!methods[methodName])
throw new Error(`Method "${methodName}" does not exist!`)
middleware.every((mid) => mid(methodName, ...args) !== false) &&
methods[methodName](...args)
},
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment