Last active
July 30, 2018 18:42
-
-
Save arleighdickerson/df30fd9d0fa6873983785e244f9d3b59 to your computer and use it in GitHub Desktop.
asynchronously configure a feathers application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ============================================================================ | |
// Author: Arleigh Dickerson | |
// (adapted from https://github.com/eliaslfox/lazy-chain) | |
// ============================================================================ | |
const _ = require('lodash'); | |
const Deferred = require('./Deferred'); | |
const pipe = Symbol('asyncBuilder.lazyHander.pipe'); | |
const lazyHandler = app => ({ | |
get(methods, methodName) { | |
switch (methodName) { | |
case pipe: | |
return async (obj) => { | |
for (const {name, args} of methods) { // eslint-disable-line | |
if (name === 'configure') { | |
await obj[name].call(app, ...args); // eslint-disable-line | |
} else { | |
obj[name](...args); | |
} | |
} | |
return obj; | |
}; | |
default: | |
methods.push({ name: methodName }); | |
return (() => { | |
const i = methods.length - 1; | |
return (...args) => { | |
methods[i].args = args; | |
}; | |
})(); | |
} | |
}, | |
set() { | |
throw new Error( | |
'invalid proxy handler call `set` in asyncBuilder.lazyHander' | |
); | |
}, | |
}); | |
function build(app, chain) { | |
const deferred = new Deferred(); | |
const ready = deferred.promise; | |
const start = (() => { | |
let starting = false; | |
return () => { | |
if (!starting) { | |
app.emit('beforeStart'); | |
starting = chain[pipe](app) | |
.then(_.partialRight(_.tap, (res) => { // success interceptor | |
deferred.resolve(res); | |
app.emit('afterStart'); | |
})) | |
.catch(_.partialRight(_.tap, (e) => { // failure interceptor | |
deferred.reject(e); | |
})); | |
} | |
return ready; | |
}; | |
})(); | |
Object.defineProperties(app, { | |
ready: { value: ready }, | |
start: { value: start }, | |
}); | |
return app; | |
} | |
module.exports = function asyncBuilder(app) { | |
const lazyProxy = new Proxy([], lazyHandler(app)); | |
const buildHandler = { | |
get(target, name) { | |
switch (name) { | |
case 'build': | |
return () => build(app, lazyProxy); | |
default: | |
return lazyProxy[name]; | |
} | |
}, | |
}; | |
return new Proxy({}, buildHandler); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment