-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_mailtemplates.js
106 lines (87 loc) · 2.72 KB
/
api_mailtemplates.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
var logger = require('tracer').colorConsole();
var async = require('async');
var mongoose = require("mongoose");
module.exports = function(db) {
return {
getTemplates: function(req, res, next) {
var start = process.hrtime();
var datasetid = req.params.datasetid;
var take = req.param("take", 0);
if (isNaN(take) || take <= 0 || take > 500) take = 500;
take = parseInt(take);
var skip = req.param("skip", 0);
if (isNaN(skip) || skip < 0) skip = 0;
skip = parseInt(skip);
db.MailTemplateModel.count({ dataset: datasetid }, function(err, count) {
db.MailTemplateModel.find({ dataset: datasetid }, { __v: 0 }).limit(take).skip(skip).exec(function(err, docs) {
if (err) {
logger.error(err);
return res.send(500);
}
if (!docs) {
return res.send(404);
}
var elapsed = process.hrtime(start)[1] / 1000000; // divide by a million to get nano to milli
return res.json({ duration: parseFloat(Math.round(elapsed).toFixed(0)), take: take, skip: skip, count: docs.length, total: count, results: docs});
});
});
},
getTemplate: function(req, res, next) {
var templateid = req.params.templateid;
var datasetid = req.params.datasetid;
db.MailTemplateModel.findOne({ "_id": templateid, "dataset": datasetid }, { __v: 0 }).exec(function(err, doc) {
if (err) {
logger.error(err);
return res.send(500);
}
if (!doc) {
return templateid && templateid.length > 0 ? res.send(404) : res.json(new db.MailTemplateModel());
}
return res.json(doc);
});
},
setTemplate: function(req, res, next) {
var templateid = req.params.templateid;
var datasetid = req.params.datasetid;
db.MailTemplateModel.findOne({ "_id": templateid }, { __v: 0 }).exec(function(err, doc) {
if (err) {
logger.error(err);
return res.send(500);
}
if (!doc) {
doc = new db.MailTemplateModel();
}
doc.name = req.body.name;
doc.subject = req.body.subject.replace(/<%/g, "<%").replace(/%>/g, "%>");
doc.content = req.body.content.replace(/<%/g, "<%").replace(/%>/g, "%>");
doc.dataset = datasetid;
doc.save(function (err) {
if (err) {
logger.error(err);
return res.send(500);
}
return res.json({id: doc._id});
});
});
},
deleteTemplate: function(req, res, next) {
var templateid = req.params.templateid;
db.MailTemplateModel.findOne({ "_id": templateid }, { __v: 0 }).exec(function(err, doc) {
if (err) {
logger.error(err);
return res.send(500);
}
if (!doc) {
return res.send(404);
}
doc.remove(function(err) {
if (err) {
logger.error(err);
return res.send(500);
}
return res.send(200);
});
});
}
};
};