I have a Node.js web application that's written in CoffeeScript, which has a set of "services". These various services are currently exposed as a CoffeeScript class
, which does a few things that I like.
For one, I get a method that gets ran once as the instance of the service is started. On some services this allows me to fetch authentication tokens, create connections, etc. that are requirements for said services. Using CS classes also allows me to have properties that can be referenced in the specific methods exposed to the class instance (status, helper methods, etc.)
Originally when I took over the application services were exposed similar to this:
class SchedulerService
constructor: (@msgBus, connStr) ->
# Some logic setting up service.
somePublicMethod: (cb) ->
cb()
module.exports = SchedulerService
More recently, I've taken up the habit of not exposing the class itself, but an instance of the class.
# Some code that grabs msgBus connection, dbConnStr
class SchedulerService
constructor: (@msgBus, connStr) ->
# Some logic setting up service.
somePublicMethod: (cb) ->
cb()
module.exports = new SchedulerService(msgBus, dbConnStr)
If you look at the docs these modules will be cached, allowing for these services to be required and have initialization be done once per service.
Are there any downsides to this sort of module pattern? One thing I'd have to worry about is having the module cache invalidated, but it seems like that wouldn't likely happen under normal circumstances.
Another worry is boilerplate code to grab these common values, but I feel like that's solvable by a module whose only job is to supply these sort of arguments.
Any other things that I'm missing here? Seems like a viable service pattern with CoffeeScript.