Skip to content

Commit

Permalink
Working ws for crypto
Browse files Browse the repository at this point in the history
  • Loading branch information
HugoRCD committed Oct 25, 2024
1 parent cc9c92d commit a6ba8e5
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 39 deletions.
2 changes: 1 addition & 1 deletion app/pages/app/crypto/[symbol].vue
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ let ws: WebSocket | undefined
function connect() {
const isSecure = location.protocol === 'https:'
const url = (isSecure ? 'wss://' : 'ws://') + location.host + '/_ws'
const url = `${isSecure ? 'wss' : 'ws'}://${location.host}/api/crypto/ws?symbol=${symbol}`
if (ws) {
console.log('ws', 'Closing previous connection before reconnecting...')
ws.close()
Expand Down
38 changes: 0 additions & 38 deletions server/api/crypto/[symbol]/index.ts

This file was deleted.

32 changes: 32 additions & 0 deletions server/api/crypto/ws.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { Peer } from 'crossws'
import { getQuery } from 'ufo'

let intervalId: NodeJS.Timeout

export default defineWebSocketHandler({
open(peer: Peer) {
console.log(`[ws] open ${peer}`)
const { symbol } = getQuery(peer.url)
console.log(`[ws] symbol ${symbol}`)

peer.subscribe('value')

const sendRandomNumber = () => {
const randomNumber = (Math.floor(Math.random() * 10000)).toFixed(2)
peer.send({ number: randomNumber })
}

intervalId = setInterval(sendRandomNumber, 1500)
},
message(peer, message) {
console.log(`[ws] message ${peer} ${message.text()}`)

if (message.text() === 'ping') {
peer.send('pong')
}
},
close(peer) {
console.log(`[ws] close ${peer}`)
clearInterval(intervalId)
}
})

0 comments on commit a6ba8e5

Please sign in to comment.