-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
96 lines (79 loc) · 2.22 KB
/
app.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
var express = require('express');
var app = express();
var path = require('path');
var multer = require('multer');
var fs = require('fs');
var watson = require('watson-developer-cloud');
var LanguageTranslatorV2 = require('watson-developer-cloud/language-translator/v2');
var bodyParser = require('body-parser')
var cfenv = require('cfenv');
app.use('/css', express.static('css'));
app.use('/js', express.static('js'));
app.use(bodyParser.json())
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/index.html'));
});
var uploadFolder = "uploads";
var documentConversion = new watson.DocumentConversionV1({
// username: <your_username>,
// password: <your_password>
version_date: '2015-12-01'
});
var languageTranslator = new LanguageTranslatorV2({
// username: <your_username>,
// password: <your_password>
url: 'https://gateway.watsonplatform.net/language-translator/api'
});
var upload = multer({
storage: multer.diskStorage({
destination(req, file, cb) {
cb(null, uploadFolder);
},
filename(req, file, cb) {
cb(null, `${Date.now()}-${file.originalname}`);
},
}),
});
app.post('/upload', upload.single('document'), (req, res, next) => {
if (!req.file && !req.file.path) {
return next({
error: 'Missing required parameter: file',
code: 400,
});
}
res.json({
documentId: req.file.filename,
});
});
app.get('/api/convert', (req, res, next) => {
var file = path.join(uploadFolder, req.query.documentId);
var params = {
conversion_target: 'NORMALIZED_TEXT',
file: file ? fs.createReadStream(file) : null
};
documentConversion.convert(params, (err, response) => {
if (err) {
return next(err);
} else {
res.send(response);
}
});
});
app.post('/api/translate', function(req, res, next) {
var params = {
text: req.body.data,
source: 'en',
target: 'pt'
};
languageTranslator.translate(params, function(err, data) {
if (err) {
return next(err);
} else {
res.json(data);
}
});
});
var appEnv = cfenv.getAppEnv();
app.listen(appEnv.port, '0.0.0.0', function() {
console.log("server starting on " + appEnv.url);
});