jeudi 6 août 2015

Implementing Mediator pattern in modular Node.js app

I've been using Mediator pattern in Node.js for a long time. My common approach is:

// MEDIATOR.js
// stdlib
exports.path = require('path');
// ...
// own modules
exports.db          = require('../models/db.js');
exports.redisKeeper = require('../reids/rediskepper.js');
// ...


// APP.js
var M = require('./mediator')

M.db.User.setPath(M.path(...))
// ...


// UTILS/HELPERS.js
var M = require('../mediator')

M.redisKeeper.setUser(new M.db.User(...))
// ...

You may notice, it's quite hard to access objects with M. prefix in every module. So, sometimes, I explicitly declare heavily used exports:

// UTILS/HELPERS.js
var M = require('../mediator')
  , redisKeeper = M.redisKeeper
  , User        = M.db.User

redisKeeper.setUser(new User(...))
// ...

This is more readable, but requires to declare the same exports in every module I'm accessing Mediators' objects.

Another approach is to set globally reusable objects into global object.

// MEDIATOR.js
// stdlib
global.path = require('path');
// ...
// own modules
global.db          = require('../models/db.js');
global.redisKeeper = require('../reids/rediskepper.js');
// ...

Now it's enough to call MEDIATOR.js once before app starts to avoid endless requires of the same objects in every file.

The major problem is naming conflicts, that my cause overwriting functions both in my own modules, and in 3rd-party.

So, what is the best approach to use mediator pattern in Node.js apps? Clean and without danger global assignments?

Aucun commentaire:

Enregistrer un commentaire