Forked from fluffybunnies/factory_plus_inheritance.js
Last active
September 28, 2018 19:58
-
-
Save dbercht/f6dc3f61254f0ce2cc5c27f5ff365a18 to your computer and use it in GitHub Desktop.
Factory + Inheritance
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
'use strict'; | |
/* At Config.JSON file | |
*/ | |
// Define the functions all the DAOs must implement | |
DaoInterfaces: { | |
ImportDaoInterface: { | |
ATTRS: [func1, func2, func3, func4] | |
} | |
} | |
// Define the interface | |
RegisteredDAOs: { | |
ids.grubhub: { | |
IMPORT: GrubhubImportDAO, | |
} | |
} | |
class DaoInterface { | |
// This class defines what the API is for the Specific DAO | |
// This will come into play when we dynamically generate the Factory | |
this.FUNCS = config.ImportDaoInterface | |
} | |
class ImportDaoInterface extends DaoInterface{ | |
// Define the API functions the Daos must implement: | |
FUNCS = [getOrders, FuncB, funcC] | |
/** | |
This methods contract is x, y, z | |
*/ | |
getOrders(dateRange, cb) { | |
throw 'Extend Me!' | |
} | |
} | |
class GrubhubImportDao extends ImportDaoInterface { | |
getOrders(dateRange, cb) { | |
cb(false, []) | |
} | |
} | |
function DaoFactory(id, functionality, props={}){ | |
// Can abstract config to be a class | |
// I think it makes sense to pass the DAO here too, but either way works | |
var daoKlass = config.registeredDaos[id][functionality] | |
// Meta program the wrapping | |
var ProxyWrapper = function(klass){ | |
var copyOfKlass = Object.copyPrototype(klass); | |
klass.FUNCS.forEach(function(copyOfKlass.func) { | |
// Rewrite the class to overwrite | |
klass.prototype[func] = wrapFuncsWithStats(copyOfKlass.prototype[func]) | |
}) | |
return klass | |
} | |
var wrapFuncsWithStats = function(func){ | |
return function() { | |
var cb = LAST_ARG(arguments) | |
func(arguments*, function() { | |
var err = FIRST_ARG(SCOPED_ARGS) | |
if (err) err Sentry(err); return cb(err); | |
// Stats histogram/increment | |
Stats.incr(err || success) | |
Stats.hist(timer) | |
cb(err, REST_OF_ARGS(SCOPED_ARGS)) | |
}) | |
} | |
} | |
return new ProxyWrapper(daoKlass)(props) | |
} | |
// test... | |
ImportDaoFactory('GrubhubImport').getOrders('last 3 hours', function(err,orders){ | |
console.log('orders=',orders) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment