MessageHandlers
Message handlers are basic event handlers for websocket messages. They are called message handlers because you can use ZilaWS to listen to local events such as new connections with event handlers. THe two are not the same thing.
Message or event handler?
Message handlers are for websocket messages/waiters. Event handlers are for local events like a new connection on the server side or disconnecting on the client side.
Usage
You can define MesageHandlers either on client or server side. In this example, we'll use them on the server.
- Waiter
- Send
server.ts
server.setMessageHandler("Login", (client, username: string, password: string) => {
const token: string | undefined = loginUser(username, password);
if(token) {
return `SUCCESS:token`;
}else {
return `FAIL:BadCredentials`;
}
});
client.ts
const resp = await client.waiter("Login", usernameInput, passwordInput);
server.ts
/*
In reality you'd probably use a waiter for this action too.
You can return values but the other side (the client in this example)
will only recieve the returned or resolved value if it is a waiter and not a simple send.
*/
server.setMessageHandler("LikePost", (client, postId: string) => {
//This right here is a fine case of extending the ZilaClient class
if(client.canLikePost(postId)) {
return false;
}
client.likePost(postId);
return true;
});
Read more about extending here.
client.ts
client.send("LikePost", postId);