-
Notifications
You must be signed in to change notification settings - Fork 22
/
index.js
90 lines (74 loc) · 1.93 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const Sms = require('./lib/sms');
const Email = require('./lib/email');
const _ = require('lodash');
const async = require('async');
const q = require('q');
function Notify(cfg){
if (!(this instanceof Notify)) {
return new Notify(cfg);
}
this.cfg = cfg || {};
this.email = new Email(this.cfg);
this.sms = new Sms(this.cfg);
}
const notify = {
respondWithError: function(err, method){
if ( typeof method === 'function' ) {
return method(err);
}
return method.reject(err);
},
respondWithSuccess: function(data, method){
if ( typeof method === 'function' ){
return method(null, data);
}
return method.resolve(data);
},
send: function send(opts, callback){
opts = _.extend(this.cfg, opts);
const method = !callback ? q.defer() : callback;
async.parallel([
//sms
function(cb){
if ( !this.cfg.sms || !this.cfg.sms.enabled ) {
return cb();
}
this.sms.send(opts)
.then(function(data){
cb(null, data);
})
.catch(function(err){
cb(err);
});
}.bind(this),
//email
function(cb){
if ( !this.cfg.email || !this.cfg.email.enabled ) {
return cb();
}
this.email.send(opts)
.then(function(data){
cb(null, data);
})
.catch(function(err){
cb(err);
});
}.bind(this)
], function(err, data){
if ( err ) {
return this.respondWithError(err, method);
}
//remove undefined items in data array from response
data = data.filter(function(d){
return typeof d !== 'undefined';
});
return this.respondWithSuccess(data, method);
}.bind(this));
if ( method.promise ) {
return method.promise;
}
}
};
//merge our prototype in with the default
Notify.prototype = _.merge(Notify.prototype, notify);
module.exports = Notify;