-
Notifications
You must be signed in to change notification settings - Fork 134
/
gql-subscribe.ts
58 lines (50 loc) · 1.31 KB
/
gql-subscribe.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
52
53
54
55
56
57
58
import fsPromises from "fs/promises"
import WebSocket from "ws"
import { createClient } from "graphql-ws"
if (process.argv.length <= 3) {
console.log("Please provide the path to the endpoint and path to gql file.")
process.exit(1)
}
const url = process.argv[3]
const filePath = process.argv[4]
const authToken = process.argv[5]
const variablesString = process.argv[6] || "{}"
let authParam = undefined
if (authToken) {
if (authToken.startsWith("dev_")) {
authParam = { "X-API-KEY": authToken }
} else {
authParam = { Authorization: `Bearer ${authToken}` }
}
}
const client = createClient({
url,
webSocketImpl: WebSocket,
connectionParams: authParam
})
const startSubscription = async () => {
try {
const data = await fsPromises.readFile(filePath, "utf8")
let variables = undefined
try {
variables = JSON.parse(variablesString)
} catch (err) {
console.log(err)
}
await client.subscribe(
{
query: data,
variables,
},
{
next: (data) => console.log(`Data: ${JSON.stringify(data)}`),
error: (err) => console.log(err, `Error: ${JSON.stringify(err)}`),
complete: () => console.log("Completed"),
},
)
} catch (err) {
console.log(`Error reading file: ${err}\n`)
process.exit(1)
}
}
startSubscription()