Created
February 11, 2012 19:10
-
-
Save half-ogre/1803665 to your computer and use it in GitHub Desktop.
Accessing Node's module cache to build a collection of event processors
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
// My app uses event sourcing, and I need a collection of all the app's event processors. | |
// I don't want to maintain this collection by hand, changing every time I add a new processor. | |
// So, I build up the collection dynamically when the app starts by examining the module cache. | |
// Caveat: I have no idea whether accessing `require.cache` is supported. | |
// Note: An event processor is any exported constructor function that ends with 'EventProcessor'. | |
exports.buildEventProcessorCollection = function() { | |
var eventProcessors = { }; | |
for (var id in require.cache) { | |
var mod = require.cache[id]; | |
for (var id in mod.exports) { | |
var exp = mod.exports[id]; | |
// in non-sample code this would probably be an endsWith function added to String's prototype. | |
if (id.indexOf("EventProcessor", id.length - 14) !== -1 && typeof(exp) === 'function') | |
eventProcessors[id] = new exp(); | |
} | |
} | |
return eventProcessors; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment