-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.ts
54 lines (51 loc) · 1.92 KB
/
api.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
export const api = {
launchExcel: async function () {
return await callAPI('launchExcel', ...arguments) as string
},
getActiveExcelRow: async function () {
return await callAPI('getActiveExcelRow', ...arguments) as {
result: 'ExcelNotRunning'|'SheetNotReady'|'ExcelTempError'|'Success',
fileName: string,
sheetName: string,
row: number,
headings: string[],
data: string[]
}
},
reviewActiveExcelRow: async function (col: number /* 1 based index*/, value: string) {
return await callAPI('reviewActiveExcelRow', ...arguments) as boolean
},
gotoRow: async function (row: number) {
return await callAPI('gotoRow', ...arguments) as boolean
},
navigateRow: async function (offset: number) {
return await callAPI('navigateRow', ...arguments) as boolean
}
}
export type BackendAPI = typeof api
let ws: WebSocket | null = null
let requestID = 0
const pendingPromises = new Map<number, (value: any) => void>()
async function getWebSocket() {
if (!ws) {
const proto = window.location.protocol
const host = window.location.hostname
const params = new URLSearchParams(window.location.search)
const port = params.get('apiPort') || '22311'
ws = new WebSocket(`${proto === 'https:' ? 'wss:' : 'ws:'}//${host}:${port}`)
ws.onclose = () => { close() }
ws.onmessage = e => {
const { id, result } = JSON.parse(e.data)
pendingPromises.get(id)!(result)
pendingPromises.delete(id)
}
await new Promise(resolve => ws!.onopen = resolve)
}
return ws
}
// call api using web socket
export async function callAPI(cmd: string, ...args: any[]) {
const ws = await getWebSocket()
ws.send(JSON.stringify({ id: ++requestID, cmd, args }))
return new Promise(resolve => pendingPromises.set(requestID, resolve))
}