Skip to content

Instantly share code, notes, and snippets.

@ganeshpatil0101
Created October 13, 2022 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ganeshpatil0101/1e85473d4e4893c7217c7e3eadd2f01e to your computer and use it in GitHub Desktop.
Save ganeshpatil0101/1e85473d4e4893c7217c7e3eadd2f01e to your computer and use it in GitHub Desktop.
Server Sent Event Example 2
const sendApiCall = document.getElementById('sendApiCall');
const output = document.getElementById('output');
const URL = (location.host === 'localhost:1234') ? '//localhost:3000/apitest' : 'https://righteous-quiet-sphynx.glitch.me/apitest';
const EURL = (location.host === 'localhost:1234') ? '//localhost:3000/esource' : 'https://righteous-quiet-sphynx.glitch.me/esource';
sendApiCall.addEventListener('click', () => {
// send api call
addLogs('Requesting server to process large data');
document.body.style.cursor = 'wait';
fetch(URL).then((res) => {
return res.json();
}).then((result) => {
addLogs(result.data);
// Event Source Object
let eventStream = new EventSource(`${EURL}`);
eventStream.addEventListener('open', () => {
console.log("Connected and subscribed to channel ");
});
eventStream.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
console.log(' eventStream data', data);
addLogs(data.msg);
document.body.style.cursor = 'default';
eventStream.close();
});
eventStream.addEventListener('error', (err) => {
document.body.style.cursor = 'default';
console.error("EventSource failed:", err);
});
});
});
function addLogs(log) {
const p = document.createElement('p');
p.innerHTML = log;
output.appendChild(p);
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript Event Source Examples</title>
<meta charset="UTF-8" />
</head>
<body>
<h1>Event Source Example 2</h1>
<div id="app">
<form id="realTimeForm">
<fieldset>
<legend> Process large dataset on server scenario </legend>
<div>
<p> Below button will send api call send asynchronous call to server that start processing large dataset.
& API will return 200 status code immediately. Server will start processing large dataset.
Rather than waiting for the status of processing i.e. completed or not, or creating pulling mechanism to check status is
bad user experience. We can take advantage of Event Source Object where server can send notification to client once processing is completed.
</p>
<button type="button" id="sendApiCall" > SEND API CALL </button>
</div>
<br />
<div>
<fieldset>
<legend> Output </legend>
<div id="output">
</div>
</fieldset>
</div>
</fieldset>
</form>
</div>
<script src="./eventSourceExample2.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment