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?

1 Answer 1

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]);
Sign up to request clarification or add additional context in comments.

5 Comments

totally forgot the module required by require() doesn't have a 'class'name. Only reference to the name is the filename.
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.
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 I'm not aware of your workflow, I'm just throwing out ideas in the wild.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.