This repository has been archived by the owner on Mar 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
94 lines (81 loc) · 2.82 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
93
94
#!/usr/bin/env node
/*jshint esversion: 8 */
require("dotenv").config();
const AppConfig = require("./configurations/appConfig");
const Hapi = require('@hapi/hapi');
const Pack = require("./package.json");
const Joi = require("@hapi/joi");
(() => {
'use strict';
/**
* Post-processing of text
* @param {String} text The English text as string
* @param {String} lang The language to translate to
* @returns {String} The translated text
*/
const PostProcessText = (text, lang) => {
try {
const postProcess = require(`./translations/${lang}.json`);
postProcess.forEach(p => {
var regexString = `\\b(${p.search})\\b`;
var re = new RegExp(regexString, "g");
text = text.replace(re, p.replace);
});
// Fixes punctuation errors
const punctuations = require(`./translations/all.json`);
punctuations.forEach(s => {
text = text.split(s.search).join(s.replace);
});
return text;
}
catch (ex) {
// File not found, just return the text
console.error(ex);
return text;
}
};
/**
* Translates the text array from English to a specified language
* @param {Array<String>} inputText The English text as array
* @param {String} toLanguage The language to translate to
* @returns {String} The translated text
*/
const TranslateText = async (inputText, toLanguage) => PostProcessText(inputText.join(" "), toLanguage);
const init = async () => {
const server = Hapi.server({
port: AppConfig.PORT,
host: AppConfig.HOST
});
server.validator(Joi);
server.route({
method: 'GET',
path: '/health',
handler: async (request, h) => {
return { name: Pack.name, version: Pack.version, timestamp: new Date().toISOString() };
}
});
console.info(`${Pack.name} health service is running on ${server.info.uri}/health`);
server.route({
method: 'POST',
path: '/',
options: {
validate: {
payload: {
text: Joi.string().required(),
to: Joi.string().required()
}
}
},
handler: async (request, h) => {
return TranslateText(request.payload.text.split(" "), request.payload.to).then(res => res).catch(err => err);
}
});
await server.start();
console.info(`${Pack.name} running on ${server.info.uri}/`);
};
process.on('unhandledRejection', (err) => {
console.info(err);
process.exit(1);
});
init();
})();