Skip to content

Commit

Permalink
Improve app
Browse files Browse the repository at this point in the history
  • Loading branch information
jramcast committed Jun 16, 2023
1 parent c355a00 commit 29ba924
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 47 deletions.
1 change: 1 addition & 0 deletions images-ubi/apps/greetings/.containerignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.git
.npm
.containerignore
node_modules
Containerfile
13 changes: 6 additions & 7 deletions images-ubi/apps/greetings/Containerfile
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
FROM registry.access.redhat.com/ubi9/nodejs-18-minimal:1-51
FROM registry.access.redhat.com/ubi9/nodejs-18-minimal

# Use root user to listen on port 80
USER root


# Application listens on this port
ENV PORT=80
EXPOSE ${PORT}

# Install application dependencies
COPY package*.json ./
RUN npm ci --omit=dev
# Add application sources
ADD . $HOME

# Copy the application source code
COPY . .
# Install dependencies.
# Clean up cache when finished.
RUN npm ci --omit=dev && rm -rf .npm

# Run the server
CMD npm start
93 changes: 93 additions & 0 deletions images-ubi/apps/greetings/LocalizationService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/**
* Simulate an external localization service
*/
const fs = require("fs").promises;


const TRANSLATIONS = {
"greeting": {
"de-de": "Guten tag",
"en-us": "Hi!",
"es-es": "Hola, ¿que tal?",
"fr-be": "Bonjour, ça va bien?",
"it-it": "Ciao, come stai?",
"ca": "Bon dia",
"pt-pt": "Olá, tudo bem?",
"hi": "Namaste",
"nl-nl": "Hallo",
"no-no": "Hei!",
"el": "Yassou",
"cs": "Ahoj!",
"pl": "Cześć!",
"sv-se": "Hej",
"ru": "Privet",
"tr": "Selam"
}
}


async function translate(key, locale) {
let translated;

try {
translated = await readFromFileCache(key, locale);
console.info(`${locale} '${key}' found in cache`);
} catch (error) {
// Only handle the not found case (ENOENT)
if (error.code !== "ENOENT") {
throw err;
}

translated = await getTranslationFromExternalService(key, locale);

await writeToFileCache(key, locale, translated);
}

return translated;
}


async function readFromFileCache(key, locale) {
const buffer = await fs.readFile(generateCacheFilename(key, locale));
return buffer.toString();
}


function writeToFileCache(key, locale, value) {
return fs.writeFile(generateCacheFilename(key, locale), value);
}


function generateCacheFilename(key, locale) {
return `/var/cache/translation_${key}_${locale}`;
}


function getTranslationFromExternalService(key, locale) {
// Simulate a network delay of 500 millis
return new Promise((resolve) => {
setTimeout(() => {
const translated = TRANSLATIONS[key][locale];
resolve(translated);
}, 500);
});
}


function getSupportedLocaleIDs() {
return Object.keys(TRANSLATIONS.greeting);
}


function getRandomLocaleID() {
const locales = getSupportedLocaleIDs();
const localeIndex = Math.floor(Math.random() * locales.length);
return locales[localeIndex];
}


module.exports = {
translate,
getRandomLocaleID,
getSupportedLocaleIDs
}
68 changes: 30 additions & 38 deletions images-ubi/apps/greetings/index.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,39 @@
const os = require("os");
const http = require("http");
const localization = require("./LocalizationService");


const hostname = "0.0.0.0";
const userInfo = os.userInfo();
const port = process.env.PORT || 80;
const greetings = [
"Guten tag",
"Hi!",
"Hello, how are you?",
"Hola, ¿que tal?",
"Bonjour, ça va bien?",
"Ciao, come stai?",
"Bon dia",
"Salve",
"Olá, tudo bem?",
"Namaste",
"Hallo",
"Hei!",
"Yassou",
"Ahoj!",
"Cześć!",
"Hej",
"Hey",
"Privet",
"Annyeong",
"Selam"
];


console.log(`User ID: ${userInfo.uid}, group ID: ${userInfo.gid}`);


http
.createServer(handleRequest)
.listen(port, hostname, () => {
console.log(`Server running as at http://${hostname}:${port}/`);
});


function handleRequest(req, res) {
const randomGreetingIndex = Math.floor(Math.random() * greetings.length);
const message = greetings[randomGreetingIndex];
const port = process.env.PORT || 8080;


main();


async function main() {
console.info(`Running with user ID: ${userInfo.uid}, group ID: ${userInfo.gid}`);

console.info("Verifying file cache...");
await localization
.translate("greeting", "en-us")
.catch((error) => {
console.error("File cache does not work due to", error);
});

console.info("Starting server...");
http
.createServer(handleRequest)
.listen(port, hostname, () => {
console.log(`Server listening at http://${hostname}:${port}/`);
});
}


async function handleRequest(req, res) {
// Return a greeting message in a random language
const locale = localization.getRandomLocaleID();
const message = await localization.translate("greeting", locale);

res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
Expand Down
4 changes: 2 additions & 2 deletions images-ubi/apps/greetings/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 29ba924

Please sign in to comment.