app.js
2.9 KB
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
107
108
109
110
/**
* Author: Jonathan Lincoln Brilhante
* Email: jonathan.lincoln.brilhante@gmail.com
*
* Author: Wesnydy Lima Ribeiro
* Email: wesnydy@lavid.ufpb.br
*/
'use strict';
/**
* Module dependencies.
*/
var express = require('express');
var shortid = require('shortid');
var amqp = require('amqplib/callback_api');
/**
* Express application and router object.
*/
var app = express();
var router = express.Router();
/**
* Function to send text to the queue.
*/
function sendToQueue(id, text, queue, durability, res) {
amqp.connect('amqp://localhost', function(err, conn) {
if(err) {
res.json({message : err});
throw err;
}
conn.createChannel(function(err, ch) {
if(err) {
res.json({message : err});
throw err;
}
ch.assertQueue(queue, {durable : durability});
ch.sendToQueue(queue, new Buffer(text), {correlationId : id});
try {
ch.close();
}
catch (alreadyClosed) {
console.log(alreadyClosed.stackAtStateChange);
}
});
setTimeout(function() { conn.close(); }, 500000);
});
}
/**
* Function to receive gloss from the queue.
*/
function receiveFromQueue(id, queue, durability, res) {
amqp.connect('amqp://localhost', function(err, conn) {
if(err) {
res.json({message : err});
throw err;
}
conn.createChannel(function(err, ch) {
if(err){
res.json({message : err});
throw err;
}
ch.assertQueue(queue, {durable : durability});
ch.consume(queue, function(msg) {
if (msg.properties.correlationId === id) {
ch.ack(msg);
res.send(msg.content.toString())
try {
ch.close();
}
catch (alreadyClosed) {
console.log(alreadyClosed.stackAtStateChange);
}
}
else {
ch.reject(msg);
}
}, {noAck : false});
});
setTimeout(function() { conn.close(); }, 500000);
});
}
/**
* Route to process text and return gloss.
*/
router.get('/', function(req, res) {
var id = shortid.generate();
var text = req.params.text;
sendToQueue(id, text, 'texts', false, res);
sendToQueue(id, text, 'log', true, res);
receiveFromQueue(id, 'glosses', false, res);
});
/**
* Register routes with prefix '/translate'.
*/
app.use('/translate', router);
/**
* Error handler.
*/
app.use(function(err, req, res) {
res.status(err.status || 500);
json({ message: err.message, error: err });
});
module.exports = app;