express-toastr
Version:
A toastr.js middleware for ExpressJS 4
110 lines (98 loc) • 2.83 kB
JavaScript
// Generated by CoffeeScript 1.8.0
(function() {
var add, clear, entities, render, _, _defaultOptions, _escape, _toasts,
__slice = [].slice;
entities = require('entities');
_ = require('lodash');
_defaultOptions = {};
_escape = function(string) {
return entities.encodeHTML(string).replace("'", "\\'");
};
_toasts = {
get: function(req) {
return req.flash('_toasts');
},
set: function(req) {
return req.flash('_toasts', req._toasts);
}
};
add = function(req, type, message, title, options) {
var _ref;
if (title == null) {
title = '';
}
if (options == null) {
options = {};
}
if (((_ref = req.session.flash) != null ? _ref._toasts : void 0) != null) {
req.session.flash._toasts = [];
}
req._toasts.push({
type: type,
message: message,
title: title,
options: options
});
return _toasts.set(req);
};
clear = function(req) {
req._toasts = [];
return _toasts.set(req);
};
render = function(req) {
var args, options, output, previousOptions, toast, toasts, _i, _len;
toasts = _toasts.get(req);
if (!toasts.length) {
return;
}
output = '<script type="text/javascript">';
previousOptions = {};
for (_i = 0, _len = toasts.length; _i < _len; _i++) {
toast = toasts[_i];
options = _.defaults(toast.options, _defaultOptions);
if (!_.isEqual(previousOptions, options)) {
output += "toastr.options=" + (JSON.stringify(options)) + ";";
}
previousOptions = options;
args = [];
args.push(_escape(toast.message));
if (toast.title) {
args.push(_escape(toast.title));
}
args = args.map(function(arg) {
return "'" + arg + "'";
});
output += "toastr." + toast.type + "(" + (args.join(',')) + ");";
}
output += '</script>';
return output;
};
module.exports = function(options) {
if (options == null) {
options = {};
}
_defaultOptions = options;
return function(req, res, next) {
req._toasts = [];
req.toastr = {
add: add.bind(null, req),
info: function() {
return this.add.apply(this, ['info'].concat(__slice.call(arguments)));
},
warning: function() {
return this.add.apply(this, ['warning'].concat(__slice.call(arguments)));
},
error: function() {
return this.add.apply(this, ['error'].concat(__slice.call(arguments)));
},
success: function() {
return this.add.apply(this, ['success'].concat(__slice.call(arguments)));
},
clear: clear.bind(null, req),
render: render.bind(null, req)
};
return next();
};
};
}).call(this);
//# sourceMappingURL=index.js.map