34 lines
967 B
JavaScript
34 lines
967 B
JavaScript
import {Controller} from '@hotwired/stimulus';
|
|
|
|
/*
|
|
* The following line makes this controller "lazy": it won't be downloaded until needed
|
|
* See https://github.com/symfony/stimulus-bridge#lazy-controllers
|
|
*/
|
|
/* stimulusFetch: 'lazy' */
|
|
export default class extends Controller {
|
|
// ...
|
|
connect() {
|
|
const topic = this.data.get('topic');
|
|
const mercureHubUrl = 'https://localhost/.well-known/mercure';
|
|
const eventSource = new EventSource(`${mercureHubUrl}?topic=${topic}`);
|
|
|
|
eventSource.onmessage = (event) => {
|
|
const data = JSON.parse(event.data);
|
|
console.log('Received Mercure update:', data);
|
|
|
|
this.dispatchAlert(data.message, data.status);
|
|
};
|
|
|
|
eventSource.onerror = (event) => {
|
|
console.error('EventSource failed:', event);
|
|
};
|
|
}
|
|
|
|
dispatchAlert(message, level) {
|
|
const event = new CustomEvent('alert:show', {
|
|
detail: { message: message, level: level }
|
|
});
|
|
window.dispatchEvent(event);
|
|
}
|
|
}
|