This repository has been archived by the owner on Aug 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
59 lines (48 loc) · 2.22 KB
/
server.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
const Koa = require('koa');
const Router = require('koa-router');
const BodyParser = require('koa-bodyparser');
const Request = require('request-promise-native');
const app = new Koa();
const router = new Router();
const defaultLanguageCode = "de";
router.get("/probe", ctx => ctx.status = 200); // Liveness / Readiness Probe
router.post("/v1/events/address-update", async ctx => {
let body = ctx.request.body;
if (body && body.address && body.address.id && body.address.countryName) {
let originalCountryName = body.address.countryName;
let canonicalCountryName = await getCanonicalCountryName(originalCountryName);
if (canonicalCountryName !== originalCountryName) {
Request.put(`${process.env.GATEWAY_URL}/v1/address/${body.address.id}`, {json: true, body: {countryName: canonicalCountryName}});
console.log(canonicalCountryName);
}
ctx.status = 200; // Success Status Code
return;
}
ctx.status = 400; // Bad Request Status Code
});
app.use(BodyParser()).use(router.routes()).use(router.allowedMethods());
const server = app.listen(parseInt(process.env.PORT));
process.on("SIGTERM", () => server.close()); // Stop Server if SIGTERM signal arrives
async function getCanonicalCountryName(countryName) {
let countryUppercaseName = countryName.toUpperCase();
let countryList = await Request.get(process.env.COUNTRYLIST_ENDPOINT, {json: true});
let matchingCountries = countryList.filter((country) => {
if (country.name.toUpperCase() === countryUppercaseName)
return true;
if (country.altSpellings.some((countrySpelling) => {
if (countrySpelling.toUpperCase() === countryUppercaseName)
return true;
}))
return true;
if (Object.keys(country.translations).some((translationKey) => {
let translation = country.translations[translationKey];
if (translation && translation.toUpperCase() === countryUppercaseName)
return true;
}))
return true;
});
if (matchingCountries.length === 1) {
return matchingCountries[0].translations[defaultLanguageCode] || matchingCountries[0].name;
}
return countryName;
}