Auto-register posts for updates

This commit is contained in:
Pierre HUBERT 2020-04-01 18:45:29 +02:00
parent 27d7c526b8
commit f3cf290822
3 changed files with 62 additions and 5 deletions

View File

@ -136,7 +136,7 @@ class UserWebSocket {
static SendRequest(title, data) { static SendRequest(title, data) {
// Send request // Send request
return new Promise((res, err) => { return new Promise((res, err) => {
if(this.ws.readyState != WebSocket.OPEN) if(!this.hasOwnProperty("ws") || this.ws.readyState != WebSocket.OPEN)
throw new Error("WebSocket is not open!"); throw new Error("WebSocket is not open!");
// Determine unique request ID // Determine unique request ID

View File

@ -4,7 +4,7 @@
* @author Pierre HUBERT * @author Pierre HUBERT
*/ */
ComunicWeb.components.posts.interface = { const PostsInterface = {
/** /**
* Get user posts * Get user posts
@ -227,6 +227,49 @@ ComunicWeb.components.posts.interface = {
//Perform the request //Perform the request
ComunicWeb.common.api.makeAPIrequest(apiURI, params, true, callback); ComunicWeb.common.api.makeAPIrequest(apiURI, params, true, callback);
},
_registerCount: {},
/**
* Register for post updates
*
* @param {Number} postID Target post ID
*/
register: async function(postID) {
if(!this._registerCount.hasOwnProperty(postID)) {
await ws("$main/register_post", {postID: postID});
this._registerCount[postID] = 1;
}
else
this._registerCount[postID]++;
},
/**
* Unregister of post updates
*
* @param {Number} postID Target post ID
*/
unregister: async function(postID) {
// Auto unregister all remaining registered posts if websocket is closed
if(!UserWebSocket.IsConnected)
this._registerCount = {}
if(!this._registerCount.hasOwnProperty(postID))
return;
this._registerCount[postID]--;
if(this._registerCount[postID] == 0) {
await ws("$main/unregister_post", {postID: postID});
delete this._registerCount[postID];
}
},
} }
} ComunicWeb.components.posts.interface = PostsInterface;
document.addEventListener("wsClosed", () => {
PostsInterface._registerCount = {}
});

View File

@ -900,6 +900,20 @@ ComunicWeb.components.posts.ui = {
//Load comments (if possible) //Load comments (if possible)
if(info.comments != null) if(info.comments != null)
ComunicWeb.components.comments.ui.display(info.comments, info.ID, postRoot); ComunicWeb.components.comments.ui.display(info.comments, info.ID, postRoot);
// Register for post updates
PostsInterface.register(info.ID);
// Auto-unregister when the post goes out of scope
const ev = async (e) => {
if(postRoot.isConnected)
return;
document.removeEventListener("openPage", ev);
PostsInterface.unregister(info.ID);
}
document.addEventListener("openPage", ev);
}, },
/** /**