-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
92 lines (82 loc) · 2.49 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
91
92
var restify = require("restify");
var bodyParser = require("restify-plugins").bodyParser;
var server = restify.createServer();
var cfenv = require("cfenv");
var appEnv = cfenv.getAppEnv();
var packageJson = require("./package.json");
var mongoose = require("mongoose");
var Notification = require("./notification/model.js").Notification;
var corsMiddleware = require("restify-cors-middleware");
var amqp = require("amqplib");
function sendJsonMessage(message) {
return amqp
.connect(appEnv.getServiceURL("notification-mq"))
.then(function(conn) {
return conn
.createChannel()
.then(function(ch) {
return ch
.assertQueue("notifications", { durable: false })
.then(function() {
ch.sendToQueue(
"notifications",
Buffer.from(JSON.stringify(message))
);
return ch.close();
})
.catch(console.warn);
})
.finally(function() {
return conn.close();
});
})
.catch(console.warn);
}
var cors = corsMiddleware({
origins: ["*"],
allowHeaders: [],
exposeHeaders: []
});
server.pre(cors.preflight);
server.use(cors.actual);
server.use(bodyParser());
server.get("/", function(req, res, next) {
var apiInfo = {
name: packageJson.name,
version: packageJson.version
};
return res.send(apiInfo);
});
server.get("/notification", function(req, res, next) {
Notification.find()
.exec()
.then(function(notifications) {
return res.send(notifications);
});
});
server.post("/notification", function(req, res, next) {
var notification = new Notification();
notification.text = req.body.text;
notification.save().then(function(savedNotification) {
console.log("Saved notification " + savedNotification.text);
sendJsonMessage(savedNotification);
return res.send(204, savedNotification);
});
});
server.del("/notification/:notificationid", function(req, res, next) {
Notification.findByIdAndRemove(req.params.notificationid, function(
removedNotification
) {
return res.send(204);
});
});
if (process.env.LOADER_IO_KEY) {
server.get("/" + process.env.LOADER_IO_KEY, function(req, res, next) {
res.setHeader("content-type", "text/plain");
return res.send(process.env.LOADER_IO_KEY);
});
}
mongoose.connect(appEnv.getServiceURL("notification-db"));
server.listen(appEnv.port, appEnv.bind, function() {
console.log("server listening at %s on port %s", appEnv.bind, appEnv.port);
});