dimanche 14 août 2016

Design patterns: Using es6 export const for dependency injection

I'been thinking about the idea to implement dependency injection in my express app built using es6. The actual project looks like this:

/controllers/myController.controller.js

import express from 'express';
import MyModel from '/models/myModel.model.js';

class MyController{
  constructor(){
    this.router = express.Router();
  }
  getAll(){
    var modelInstance = new MyModel();
    this.router.get('/', (req , res) => {
      res.send(modelInstance.getData());
    });
  }
}

/models/myModel.model.js

export class MyModel{
  constructor(){
  }
  getData(){
    return 'it\'s working';
  }
}

But i think that a better idea is export a instance of class like this:

/models/myModel.model.js

class MyModel{
  constructor(){
  }
  getData(){
    return 'it\'s working';
  }
}
//export a new instance
export const ModelInstance = new MyModel();

And then modify the controller like this

/controllers/myController.controller.js

import express from 'express';
//inject a new instance of the model
import {modelInstance} from '/models/myModel.model.js';

class MyController{
  constructor(){
    this.router = express.Router();
  }
  getAll(){
    this.router.get('/', (req , res) => {
      res.send(modelInstance.getData());
    });
  }
}

I don't know if my idea it is correct, but i think that this example it's a good application about this pattern.

What do you think about this?

Aucun commentaire:

Enregistrer un commentaire