61 lines
1.3 KiB
JavaScript
61 lines
1.3 KiB
JavaScript
import WebSocket from "ws"
|
|
|
|
export default class FormsClient {
|
|
constructor(url = "ws://localhost:4001") {
|
|
this.url = url
|
|
this.ws = null
|
|
this.seq = 0
|
|
this.handlers = new Map()
|
|
}
|
|
|
|
connect() {
|
|
this.ws = new WebSocket(this.url)
|
|
|
|
this.ws.on("message", msg => this._onMessage(msg))
|
|
this.ws.on("open", () => console.log("[forms] connected"))
|
|
this.ws.on("close", () => console.log("[forms] disconnected"))
|
|
}
|
|
|
|
append(form, data) {
|
|
this.ws.send(JSON.stringify({
|
|
op: "append",
|
|
form,
|
|
data
|
|
}))
|
|
}
|
|
|
|
watch(form, handler) {
|
|
if (!this.handlers.has(form)) {
|
|
this.handlers.set(form, new Set())
|
|
}
|
|
|
|
this.handlers.get(form).add(handler)
|
|
|
|
this.ws.send(JSON.stringify({
|
|
op: "replay",
|
|
form,
|
|
fromSeq: this.seq
|
|
}))
|
|
}
|
|
|
|
_onMessage(raw) {
|
|
const msg = JSON.parse(raw.toString())
|
|
|
|
if (msg.type === "hello") {
|
|
this.seq = msg.seq
|
|
return
|
|
}
|
|
|
|
if (msg.type === "form:update") {
|
|
this.seq = msg.seq
|
|
|
|
const set = this.handlers.get(msg.form)
|
|
if (set) {
|
|
for (const fn of set) {
|
|
fn(msg.data, msg)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|