Files
notifications-admin/app/assets/javascripts/socketio.js

84 lines
2.3 KiB
JavaScript
Raw Normal View History

2025-04-09 16:57:42 -07:00
function debounce(func, wait) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
2025-04-18 11:45:18 -07:00
document.addEventListener('DOMContentLoaded', function () {
const isJobPage = window.location.pathname.includes('/jobs/');
2025-04-09 16:57:42 -07:00
if (!isJobPage) return;
2025-04-18 11:45:18 -07:00
const jobEl = document.querySelector('[data-job-id]');
2025-04-10 12:35:04 -07:00
const jobId = jobEl?.dataset?.jobId;
2025-04-18 11:45:18 -07:00
const featureEnabled = jobEl?.dataset?.feature === 'true';
2025-04-21 15:56:19 -07:00
const apiHost = jobEl?.dataset?.host;
2025-04-10 12:35:04 -07:00
2025-04-09 16:57:42 -07:00
if (!jobId) return;
2025-04-10 12:35:04 -07:00
if (featureEnabled) {
2025-04-21 15:56:19 -07:00
const socket = io(apiHost);
2025-04-10 12:35:04 -07:00
2025-05-22 12:03:18 -07:00
socket.on('connect_error', (err) => {
console.error('Socket connect_error:', err);
});
socket.on('error', (err) => {
console.error('Socket error:', err);
});
2025-04-18 11:45:18 -07:00
socket.on('connect', () => {
socket.emit('join', { room: `job-${jobId}` });
2025-04-10 12:35:04 -07:00
});
2025-04-09 16:57:42 -07:00
2025-04-18 11:45:18 -07:00
window.addEventListener('beforeunload', () => {
socket.emit('leave', { room: `job-${jobId}` });
2025-04-10 12:35:04 -07:00
});
2025-04-10 12:35:04 -07:00
const debouncedUpdate = debounce((data) => {
updateAllJobSections();
}, 1000);
2025-03-27 14:27:43 -07:00
2025-04-18 11:45:18 -07:00
socket.on('job_updated', (data) => {
2025-04-10 12:35:04 -07:00
if (data.job_id !== jobId) return;
debouncedUpdate(data);
});
}
2025-04-09 16:57:42 -07:00
function updateAllJobSections() {
const resourceEl = document.querySelector('[data-socket-update="status"]');
const url = resourceEl?.dataset?.resource;
if (!url) {
2025-04-18 11:45:18 -07:00
console.warn('No resource URL found for job updates');
2025-04-09 16:57:42 -07:00
return;
}
fetch(url)
.then((res) => res.json())
.then(({ status, counts, notifications }) => {
const sections = {
status: document.querySelector('[data-socket-update="status"]'),
counts: document.querySelector('[data-socket-update="counts"]'),
2025-04-18 11:45:18 -07:00
notifications: document.querySelector(
'[data-socket-update="notifications"]'
),
2025-04-09 16:57:42 -07:00
};
if (status && sections.status) {
sections.status.innerHTML = status;
}
if (counts && sections.counts) {
sections.counts.innerHTML = counts;
}
if (notifications && sections.notifications) {
sections.notifications.innerHTML = notifications;
}
})
.catch((err) => {
2025-04-18 11:45:18 -07:00
console.error('Error fetching job update partials:', err);
2025-04-09 16:57:42 -07:00
});
}
});