-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathindex.ts
51 lines (42 loc) · 1.06 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { Buffer } from 'buffer'
// Endpoints
export const PORT = process.env.EXPRESS_PORT || 3000
export const endpoint = {
browser: `ws://localhost:${PORT}/browser`,
server: `ws://localhost:${PORT}/server`
}
// Serialization
export enum Topic {
Chat_Message = 'chat/message',
}
export enum Endpoint {
Browser = 'Browser',
Server = 'Server',
}
export interface ActionEvent<T> {
endpoint: Endpoint
topic: Topic
payload: T
}
export const formatPrefix = (endpoint: Endpoint, topic: Topic) =>
Buffer.from(JSON.stringify([endpoint, topic])).slice(0, -2) // removes "] for topic generalization
export const encodeActionEvent = <T>(
endpoint: Endpoint,
topic: Topic,
payload: T,
) => JSON.stringify([endpoint, topic, payload])
export const decodeActionEvent = <T>(msg: Buffer): ActionEvent<T> => {
const [endpoint, topic, payload] = JSON.parse(msg.toString('utf-8')) as [
Endpoint,
Topic,
T,
]
return { endpoint, topic, payload }
}
// Message Types
export interface ChatMessage {
id: string
user: string
text: string
time: number
}