Incredibly simple, Dependency Injection for isomorphic Javascript applications.
OTHER License
Incredibly simple, Dependency Injection for isomorphic Javascript applications.
When using libraries such as React, React Router, & RefluxJS, you'll find that singletons don't work well on the server-side for Actions, Routes, Stores, & Views, as they share state between all requests.
On the client-side, each user's browser serves as a container to scope functions. Similarly, Diez introduces a container for each request on the server.
Luckily, all it takes is to turn your singletons into factories by wrapping
them with function(...) { return ...; }
& registering them via diez.register
.
Diez will retrieve them while isolating instances to a single container-per-request.
Suppose you're rendering your React view on the server with React Router,
but rely on request
-specific data, such as the user's ip
, for some reason.
$ npm install --save diez
In your application middleware:
// server.js
app.use(function(req, res, next) {
// This container & it's references are sandboxed to this request.
req.container = diez.container();
req.container.register('request', req);
});
Now, every call to req.container.get('request')
returns req
.
Before, your view is a singleton:
// MyView.js
var MyView = React.createClass({
render: function() {
<p>
Hello!
</p>
}
});
module.exports = MyView;
After, your view is a factory with dependencies defined:
// MyView.js
var diez = require('diez');
// Convert singleton to factory
var MyView = function(request) {
return React.createClass({
render: function() {
<p>
Hello, {request.ip}!
</p>
}
});
};
// Register component with dependencies
diez.register(MyView, ['request']);
module.exports = MyView;
app.get('/', function(req, res) {
// Get instantiated MyView with dependencies injected
var component = req.container.get(MyView);
var element = React.createElement(view);
res.send(React.renderToString(element));
});
That's it!
Internet Systems Consortium license
Copyright (c) 2015 Eric Clemmons
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.