-
Notifications
You must be signed in to change notification settings - Fork 0
/
translate_worker.js
101 lines (87 loc) · 2.36 KB
/
translate_worker.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
var googleTranslate = require('google-translate')('#GOOGLE_TRANSLATE_API_KEY');
// var DataSource = require('loopback-datasource-juggler').DataSource;
var worker = require('iron_worker');
var Promise = require('bluebird');
var fs = require('fs');
var path = require('path');
var params = worker.params();
var client;
// var datasource = new DataSource({
// connector : require('loopback-connector-remote'),
// name: "RemoteDS",
// url: params.loopbackServerUrl+":"+params.loopbackServerport+"/api"
// });
// var Message = client.models.Message;
// Message.attachTo(datasource);
// console.log(app.dataSources.remoteDS);
var createDatasourceFile = function(url,port){
var datasourcesFile = path.join(__dirname, 'client', 'datasources.json');
return new Promise(function(resolve,reject){
fs.writeFile(datasourcesFile,
JSON.stringify({
"db": {
"name": "db",
"connector": "memory"
},
"remoteDS": {
"url": url +'/api',
"name": "remoteDS",
"connector": "remote"
}
}, null, 2),function(err){
if(err){
reject(err);
}
else{
resolve("Datasource file created");
}
});
});
};
var setAuthToken = function(token) {
client.dataSources.remoteDS.connector.remotes.auth = {
bearer: new Buffer(token.id).toString('base64'),
sendImmediately: true
};
return Promise.resolve('Access token set for request');
};
var translateToSpanish = function(text){
return new Promise(function(resolve,reject){
googleTranslate.translate(text, 'es', function(err, translation) {
if(err){
reject(err);
}
else{
resolve(translation.translatedText);
}
});
});
};
createDatasourceFile(params.loopbackServerUrl)
.then(function(data){
console.log(data);
client = require('./client/loopback.js');
return setAuthToken(params.loopbackAccessToken);
})
.then(function(data){
console.log(data);
return translateToSpanish(params.text);
})
.then(function(data){
console.log(data);
var message = {
text : data,
senderId: params.senderId,
recieverId: params.recieverId,
created_at: new Date(),
is_read:false
};
client.models.Message.create(message, function(err, response){
if(err){
console.log(err);
}
else{
console.log(response);
}
});
});