-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
request.ts
36 lines (32 loc) · 974 Bytes
/
request.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
import type { JsonRpcRequest, JsonRpcResponse } from './types.ts'
import { makeArray } from './utils.ts'
export function send(
socket: WebSocket,
message: JsonRpcResponse | JsonRpcResponse[],
): void {
const messages = makeArray<JsonRpcResponse>(message)
messages.forEach((message) => {
message.jsonrpc = '2.0'
if (messages.length === 1) socket.send(JSON.stringify(message))
})
if (messages.length !== 1) socket.send(JSON.stringify(messages))
}
export function parseRequest(
json: string,
): (JsonRpcRequest | 'invalid')[] | 'parse-error' {
try {
const arr = makeArray(JSON.parse(json))
const res: (JsonRpcRequest | 'invalid')[] = []
for (const obj of arr) {
if (
typeof obj !== 'object' || !obj || obj.jsonrpc !== '2.0' ||
typeof obj.method !== 'string'
) res.push('invalid')
else res.push(obj)
}
if (!res.length) return ['invalid']
return res
} catch {
return 'parse-error'
}
}