make post updates read from the JSON api if there was a reconnection to keep up to date over spotty connections

merge-requests/208/head
fatchan 5 years ago
parent 1ae833479f
commit b0db29f7c7
  1. 57
      gulp/res/js/live.js

@ -3,20 +3,14 @@ window.addEventListener('DOMContentLoaded', (event) => {
const isThread = /\/\w+\/thread\/\d+.html/.test(window.location.pathname);
if (isThread) {
const posts = document.getElementsByClassName('anchor');
if (posts.length === 0) {
return; //url matches, but on a 404 page
const anchors = document.getElementsByClassName('anchor');
if (anchors.length === 0) {
return; //url matches, but on a 404 page so dont bother with the rest
}
const roomParts = window.location.pathname.replace(/\.html$/, '').split('/');
const room = `${roomParts[1]}-${roomParts[3]}`;
const thread = document.querySelector('.thread');
const socket = io({ transports: ['websocket'] });
socket.on('connect', function() {
console.log('joined room', room);
socket.emit('room', room);
});
socket.on('newPost', function(data) {
let lastPostId = anchors[anchors.length - 1].id;
const newPost = (data) => {
console.log('got new post');
lastPostId = data.postId;
const postData = data;
//create a new post
const postHtml = post({ post: postData });
@ -50,9 +44,44 @@ window.addEventListener('DOMContentLoaded', (event) => {
postId: postData.postId
}
});
//dispatch the ervent so quote click handlers, image expand, etc can be added in separate scripts by listening to the event
//dispatch the event so quote click handlers, image expand, etc can be added in separate scripts by listening to the event
window.dispatchEvent(newPostEvent);
});
}
const jsonPath = window.location.pathname.replace(/\.html$/, '.json');
const jsonCatchup = async () => {
console.log('catching up after reconnect');
let json;
try {
json = await fetch(jsonPath).then(res => res.json());
} catch (e) {
return console.error(e);
}
if (json && json.replies && json.replies.length > 0) {
const newPosts = json.replies.filter(r => r.postId > lastPostId); //filter to only newer posts
if (newPosts.length > 0) {
for (let i = 0; i < newPosts.length; i++) {
newPost(newPosts[i]);
}
}
}
}
const roomParts = window.location.pathname.replace(/\.html$/, '').split('/');
const room = `${roomParts[1]}-${roomParts[3]}`;
const thread = document.querySelector('.thread');
const socket = io({ transports: ['websocket'] }); //no polling
socket.on('connect', () => {
console.log('joined room', room);
socket.emit('room', room);
});
socket.on('disconnect', () => {
console.log('lost connection to room');
});
socket.on('reconnect', () => {
console.log('reconnected to room');
jsonCatchup();
});
socket.on('newPost', newPost);
}
});

Loading…
Cancel
Save