2

I'm writing a Node app that will generate an array of JMS queue subscriptions based on configuration pulled from a backend db. Upon initialization, I will retrieve the current state from the backend, but I then need to support inbound API calls to the Node server to add and remote subscriptions on the fly (and I'll then update the list stored in the backend).

There must only ever be one instance of this subscription array available in the entire application, and it must be the source of truth.

Example:

On init, I'd get from the API:

{
    "amysCar": {
        "name": "2016 Lamborghini Gallardo LP 550-2",
        "queue": "/queues/amysracingstats"
    },
    "bobsCar": {
        "name": "1967 Ford Mustang Shelby Shelby GT500",
        "queue": "/queues/bobsrestorationproject"
    }
}

Then let's say Bob decides he no longer wants to publish his restoration project; he'll make an API call to the Node server DELETE /projects/bobsCar. I'll remove the queue listener from the queues array and update the backend db.


In practice, I need to be able to access the JMS queues array from multiple controllers because the controller that handles the API calls is separate from the controller that handles queue subscriptions.

I am aware that singletons are notoriously difficult to write and manage in Node, are frowned upon, and are allegedly completely unnecessary because Node.js module caching supposedly only ever loads a single instance of a module. If that's correct, I could simply store the array of queue subscriptions as a private object in a module, and then require it in the API call controller.

  1. Is this true? Can I use this ability to meet my requirement?

  2. If so, how would I overwrite the initialization of the module so that I can make that initial backend call to get the current state?

  3. Am I overthinking this?

Community
  • 1
  • 1
brandonscript
  • 68,675
  • 32
  • 163
  • 220

1 Answers1

5
  1. Is this true? Can I use this ability to meet my requirement?

Yes, it is true. Just use a module property. Because of module caching, there will only be one such property.

  1. If so, how would I overwrite the initialization of the module so that I can make that initial backend call to get the current state?

I would assume that the module itself would just make the back-end call to initialize the state. It can do that when first loaded or via the first module constructor call.

  1. Am I overthinking this?

You seem to already know about module caching and how module properties can work as singletons so if you're still trying to avoid using that capability, then that would be overthinking it. But, if you're just confirming how things work before relying on it, no problem with that.

jfriend00
  • 683,504
  • 96
  • 985
  • 979