Skip to content

Commit

Permalink
move addMessage (ignore ping/pong) (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
JCtapuk committed Feb 28, 2024
1 parent 6367512 commit 69783a5
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions server/api/chat-ws.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Peer } from 'crossws';
import { getQuery } from "ufo"
import type { Peer } from "crossws";
import { getQuery } from "ufo";

const users = new Map<string, { online: boolean }>();

Expand All @@ -11,28 +11,31 @@ export default defineWebSocketHandler({
users.set(userId, { online: true });

const stats = getStats();
peer.send({ user: "server", message: `Welcome to the server ${userId}! (Online users: ${stats.online}/${stats.total})` });
peer.send({
user: "server",
message: `Welcome to the server ${userId}! (Online users: ${stats.online}/${stats.total})`,
});

peer.subscribe("chat");
peer.publish("chat", { user: "server", message: `${peer} joined!` });

},
async message(peer, message) {
console.log(`[ws] message ${peer} ${message.text()}`);

const userId = getUserId(peer);

if (message.text() === "ping") {
peer.send({ user: "server", message: "pong" });
} else {
const _message = {
user: userId,
message: message.text(),
};
peer.send(_message); // echo back
peer.publish("chat", _message);
return
}

const _message = {
user: userId,
message: message.text(),
};
peer.send(_message); // echo back
peer.publish("chat", _message);

// Store message in database
await addMessage(userId, message.text());
},

Expand All @@ -50,7 +53,7 @@ export default defineWebSocketHandler({
upgrade(req) {
return {
headers: {
"x-powered-by": "cross-ws"
"x-powered-by": "cross-ws",
},
};
},
Expand Down

0 comments on commit 69783a5

Please sign in to comment.