forked from Macrometacorp/tutorial-jsc8-stream-ws-on-cfw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (52 loc) · 1.6 KB
/
index.js
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
52
53
54
55
56
57
58
59
import template from "./template"
const jsc8 = require("jsc8")
const gdnUrl = "https://gdn.paas.macrometa.io"
const jsc8Client = new jsc8({
url: gdnUrl,
apiKey: "xxxx",
agent: fetch.bind(this),
})
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request))
})
const macrometaWsHandler = async (request) => {
let client
const { searchParams } = new URL(request.url)
const streamType = searchParams.get("streamType")
const streamName = searchParams.get("streamName")
const stream = jsc8Client.stream(streamName, true)
const consumerOTP = await stream.getOtp()
if (streamType === "producer") {
client = await stream.producer(gdnUrl.replace("https://", ""), { otp: consumerOTP }, "cloudflare")
} else {
client = await stream.consumer(
"SampleStream-my-subscription",
gdnUrl.replace("https://", ""),
{ otp: consumerOTP },
"cloudflare",
)
}
return new Response(null, {
status: 101,
webSocket: client,
})
}
async function handleRequest(request) {
try {
const pathname = new URL(request.url).pathname
switch (pathname) {
case "/":
return template()
case "/setupWebsocket":
try {
return await macrometaWsHandler(request)
} catch (error) {
throw error
}
default:
return new Response("Not found", { status: 404 })
}
} catch (err) {
return new Response(err.toString())
}
}