@dieugene/queuer
Version:
Node.js library for seamless integration with message queues through Yandex Cloud Functions
57 lines (47 loc) • 1.85 kB
JavaScript
const fetch = require("node-fetch");
function init(queuerId = process.env.QUEUER_FUNCTION_ID || 'd4eqfj8q8arbr0rrtrbk') {
function log(...args) {
if (!!process.env.LOG && process.env.LOG.includes('QUEUER')) console.log(...args);
}
async function postQueue(domain = '', body = {}, queue_url){
await postItem({domain, body, queue_url})
}
async function postItem(item) {
log('QUEUER :: POSTING :: ', JSON.stringify(item));
let body = typeof item === 'object' ? JSON.stringify(item) : item;
await fetch('https://functions.yandexcloud.net/' + queuerId, {
method: 'POST',
body,
headers: {'Content-Type': 'application/json',}
});
}
postQueue.item = postItem;
async function ensureQueueItem(input, value, field = 'queue_url') {
let items = input.data.object.messagesData,
result = true;
for (let i = 0; i < items.length; i++) {
let valueToCheck = field === 'queue_url' ? items[i].queue_url : items[i].domain;
if (value !== valueToCheck) {
console.log('!!!!!!!! >>>>>>>> GOT WRONG QUEUE ITEM ::', JSON.stringify(items[i]));
await postItem(items[i]);
result = false;
}
}
return result;
}
async function send_to_queue(input, bot_token, queue_url, domain) {
let item = input.data.object;
item.bot_token = bot_token;
item.from_queue = true;
await postQueue(domain, item, queue_url);
}
function is_from_queue(input) {
return !!input?.data?.object.from_queue
}
return {
send_to_queue, is_from_queue,
post: postQueue,
ensureQueueItem
}
}
module.exports = init;