Live Query controlled server side?


I am getting closer to finishing a turn based game that uses Moralis cloud (my sudo-server), database, and live queries.

One of the finer points I am anticipating…


  1. If a player joins the game, it subscribes live queries.
  2. If that player uses the “leave game” button, the client will request itself be unsubscribed from the live queries and the server will remove the player.

This, however, doesn’t consider if a player loses connection or just closes the browser. Is there a way to trigger cloud code if this happens?

I took a look at this part of the docs: but I’m not totally sure if it’s related or not.

Perhaps I can request sessionToken? (are these shown in the database browser?)

Any point in the right direction would be appreciated!

what you mean by this? how would session token help you?

you may be able to get the session token from a cloud function

Maybe it wont. I didnt get enough from the docs to understand the function.

If i could match a client subscription to a player when the live query is created, then check if that subscription still exists occassionally, that may work.

Is there a check a subscription in cloud code given the id?

Don’t fret we have a solution for it all haha. Moralis Websocket will do the trick

  • When a WebSocket connection to the LiveQuery server is lost you’ll get this event.
Moralis.LiveQuery.on('close', () => {
  console.log('socket connection closed');
  • This for network error checking
Moralis.LiveQuery.on('error', (error) => {

Hope this helps, and good question :v:

Thanks RayRay, but this is the code that runs on the client, right? If the user lose connection or x out the browser, the close event would not be able to alert the server…but let me know if I dont understand.

Is there anything i can do to ask moralis if a particular socket connection is still open given the id of that socket?

I suppose i could build a pinging system, but it would ve easier if i can just check socket status in cloud code. Let me know if theres any way!

Actually pinging might be the way…i need to give them a chance to reconnect or rejoin before i kick out the player.

Any thoughts?

Sorry missed this. Pinging could work, maybe make a table called ‘userPings’, and keep adding a new value to that as long as the user is playing. BUT, make sure to have a afterSave cloud func that deletes old pings.