Skip to content
This repository was archived by the owner on May 24, 2022. It is now read-only.

Commit 28b6062

Browse files
committed
abstract websockets a bit
1 parent 1632c8c commit 28b6062

4 files changed

Lines changed: 43 additions & 13 deletions

File tree

client/src/pages/GroupPhoto/GroupPhoto.js

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,9 @@ import React, { useEffect, useState } from 'react'
22
import Button from '../../components/Button'
33
import Page from '../../components/Page'
44
import { downloadFromS3 } from '../../utils/download'
5+
import { onWsEvent } from '../../websockets'
56
import './GroupPhoto.css'
67

7-
const HOST = window.location.origin
8-
.replace(/^http/, 'ws')
9-
.replace('3000', '3001')
10-
const ws = new WebSocket(HOST)
11-
12-
// `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${
13-
// window.location.hostname
14-
// }:${process.env.PORT || 3001}`,
15-
168
const GroupPhoto = () => {
179
const [isLoading, setIsLoading] = useState(true)
1810
const [isGenerating, setIsGenerating] = useState(false)
@@ -42,16 +34,14 @@ const GroupPhoto = () => {
4234

4335
useEffect(() => {
4436
getGroupPhoto()
45-
ws.onmessage = (event) => {
46-
const data = JSON.parse(event.data)
47-
if (data.id !== 'group-photo') return
37+
onWsEvent('group-photo', (data) => {
4838
if (data.status === 200) {
4939
setFile(data.data)
5040
} else {
5141
console.log(data.message, data.error)
5242
}
5343
setIsGenerating(false)
54-
}
44+
})
5545
}, [])
5646

5747
const header = <h1>Create Group Photo</h1>

client/src/websockets.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const HOST = window.location.origin.replace(/^http/, 'ws')
2+
3+
if (process.env.NODE_ENV === 'development') HOST.replace('3000', '3001')
4+
5+
export const ws = new WebSocket(HOST)
6+
7+
export const onWsEvent = (eventId, callback) => {
8+
ws.onmessage = (event) => {
9+
const data = JSON.parse(event.data)
10+
if (data.id === eventId) callback(data)
11+
}
12+
}

package-lock.json

Lines changed: 24 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,5 +53,9 @@
5353
"eslint --fix",
5454
"prettier --write"
5555
]
56+
},
57+
"optionalDependencies": {
58+
"bufferutil": "^4.0.1",
59+
"utf-8-validate": "^5.0.2"
5660
}
5761
}

0 commit comments

Comments
 (0)