jeudi 9 mai 2019

ES6 modules - best approach for creating an immutable service

I'm using the following approach for creating a singleton-like service in my application:

myService.js:

let myService = {};

myService.doSomething = function() {
    //doing something
};

export {myService};

usage in other module:

import {myService} from 'myService.js'

myService.doSomething();

export {myService};

Generally this works fine, but the problem is that it's possible to modify the service in a module that is importing it:

import {myService} from 'myService.js'

myService.doSomething = function() {
    //do something different
};

export {myService};

This is not desireable for a singleton-service, it should be immutable.

How can immutability can be achieved? Does anybody have a completely different/better approach for creating immutable services as ES6 modules?

Aucun commentaire:

Enregistrer un commentaire