Skip to content

Instantly share code, notes, and snippets.

@zo0m
Created July 17, 2019 11:15
Show Gist options
  • Save zo0m/753d16a2d4f0bfbe25d12031ed60dcec to your computer and use it in GitHub Desktop.
Save zo0m/753d16a2d4f0bfbe25d12031ed60dcec to your computer and use it in GitHub Desktop.
const moment = require('moment');
const Promise = require('bluebird');
const _ = require('underscore');
const {Logger} = require('../logger');
const translator = require('./translators');
let translationQueue = [];
let isProcessing = false;
async function processQueueItem() {
Logger.info(`TranslateQueueApiService.processQueueItem() translationQueue.length == ${translationQueue.length}`);
const nextItem = translationQueue.shift();
if (nextItem) {
const {entity, args, resolve, reject} = nextItem;
try {
const translation = await translator.translate(...args);
resolve(translation);
for (const sameEntityItem of translationQueue) {
if (sameEntityItem.entity
&& `${entity._id}` === `${sameEntityItem.entity._id}`
&& entity.updated_at >= sameEntityItem.entity.updated_at) {
sameEntityItem.resolve(translation);
const indexToRemove = translationQueue.indexOf(sameEntityItem);
translationQueue.splice(indexToRemove, 1);
Logger.info(`TranslateQueueApiService.processQueueItem() resolved too ${indexToRemove} id: ${sameEntityItem.entity._id}`);
}
}
} catch (error) {
reject(error);
}
}
if (translationQueue.length) {
setTimeout(processQueueItem, 5000 + parseInt(Math.random() * 1000 * 5)); // 5 - 10 sec
} else {
isProcessing = false;
}
}
function startQueue() {
if (isProcessing) {
return;
}
isProcessing = true;
setTimeout(processQueueItem, 5000);
}
class TranslateQueueApiService {
static async translate(entity, ...args) {
const translatePromise = new Promise((resolve, reject) => {
translationQueue.push({entity, args, resolve, reject});
startQueue();
});
return translatePromise;
}
}
module.exports = TranslateQueueApiService;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment