fjorgemota / jimple

Just a dependency injection container to NodeJS and to the browser using new ES6 features
MIT License
75 stars 12 forks source link

Shortcut function to create a provider #18

Closed homer0 closed 6 years ago

homer0 commented 6 years ago

Hi,

I have a proposal for a tiny improvement and I would like to check before sending a PR.

Here it is:

module.exports.provider = register => ({ register });

It may look silly, but I always end up creating this function on every Jimple project (and I have a few). I prefer this wrapper over having to define an object with a register method and exporting a generic register method.

Here's an example of how I use it:

const { provider } = require('...');

class MyService {
  constructor(dep1, dep2) {
    ...
  }
}

const myService = provider((c) => {
  container.set('myService', () => new MyService(
    c.get('dep1'),
    c.get('dep2')
  );
});

module.exports = {
  MyService,
  myService,
};

That way I make available the service class and the provider for it.

Let me know what you think; if you don't like it or you don't see any added value, no worries :). And if you like it, I'll send you the PR right away.

Regards.

fjorgemota commented 6 years ago

Hey.

Thank you for your suggestion!

So...you propose just to turn provider into a function exported by jimple package?

I'm not against it, even through I do not see directly any advantages over it's use. Personally, I like the method of using a module as a provider directly.

Regards.

homer0 commented 6 years ago

Hi,

Yeah, as I told you you can do something like this right now by exporting a register function;

Here's a few thing I failed to include on the first post and that are some of the reasons I prefer the wrapper:

const { provider } = require('...');

class MyService {
  constructor(dep1, dep2) {
    ...
    this.someSmartOption = 'value-by-default';
  }
}

const myServiceWithOptions = (smartOptionValue) => provider((c) => {
  container.set('myService', () => {
    const service = new MyService(
      c.get('dep1'),
      c.get('dep2')
    );

    if (smartOptionValue) {
      service.someSmartOption = smartOptionValue;
    }

    return service;
  });
});

const myService = myServiceWithOptions();

module.exports = {
  MyService,
  myService,
  myServiceWithOptions,
};

That's a basic example with "smart defaults"; I also use this same approach for services that have optional dependencies, in order to try-catch the get if the optional dependency is not registered.

I think that with the previous example is enough to show how simple is to read and implement currying with a wrapper like this.

fjorgemota commented 6 years ago

Hey.

Ok. Feel free to send a PR.

I'll work soon to release it in NPM (I have a few things that changed in the library too, like support for Proxies in ES6, to release too..).

Thanks.

homer0 commented 6 years ago

Done; I'm closing this issue and we can continue the conversation there.