0

Being fairly new to NodeJS I wonder what would be the best approach for the following 'problem'.

My main application accepts variables including a device_type and a payload. The way this payload needs to be decrypted depends on the device_type.

To avoid using a big case/switch or if-clause and to be able to just drop in a new device when needed; I'm looking for a more object oriented approach.

In PHP I would create a class for each device and 'load' them accordingly from the correct namespace with a decorator. Each class would have a decrypt() method (enforced by using contract)

How would I accomplish a same structure in nodejs?

stUrb
  • 6,612
  • 8
  • 43
  • 71

1 Answers1

1

Well, as you yourself suggest, you can write those as modules and then include them based on the device type you mention.

Assuming you have created your modules and put them in the appropriate directory

var decryptors = {
    device_type_1: 'decryptor_module_1',
    device_type_2: 'decryptor_module_2',
};

var decryptor = require(decryptors[input.device_type]);
php_nub_qq
  • 15,199
  • 21
  • 74
  • 144
  • totally forgot the module required by require() doesn't have a 'class'name. Only reference to the name is the filename. – stUrb Oct 09 '16 at 22:06
  • Furthermore you can avoid having a mapping by having a `decryptor` (or whatever) property in your device object that will return the name of the decryptor that has to be loaded, or even the object itself. – php_nub_qq Oct 09 '16 at 22:13
  • But then you should load every possible device at first, and loop through them to find the right 'decryptor' property. Sounds not efficiënt, or do i miss something? – stUrb Oct 09 '16 at 22:29
  • @stUrb I'm not aware of your workflow, I'm just throwing out ideas in the wild. – php_nub_qq Oct 10 '16 at 00:39
  • I'm willing to adjust my workflow to a better one :) For now I'll stick to the mapping-table. Is there a non-fatal way to check if the require() exists? – stUrb Oct 10 '16 at 08:51