Saturday, 15 April 2017

"doubleton" or how to have two global instances of a module

I am playing with node.js porting a webAPI currently implemented in Delphi and learning how to do things the node way.

My application uses two instances of a database-backend connected to a different DB each. Service-code can get a connection to each from one of two global instances of a connection-pool.

How would one do this in node.js?

I know how to write the pool as a module exporting a constructor so I can create two instances, configured with a different connection string. I can hold these in global variables in the main server-file or in a module holding references to various services and doing routing of requests.

But how would the individual service-modules that want to get a connection, do something with it and then return it to the pool get access?

So far I have been happy with require()-ing such shared modules everywhere I use them, so they behave as singletons and the state is shared between everywhere they are require()-ed. But how to do that if I want two (or n) instances that are configured differently?

All I can think of so far is actively injecting a reference to them everywhere. Would work, but is that the proper solution?

P.S.: I did not know up to now that Doubletons are a thing.



via Marian Aldenhövel

No comments:

Post a Comment