-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathinvoke.js
More file actions
64 lines (63 loc) · 2.02 KB
/
invoke.js
File metadata and controls
64 lines (63 loc) · 2.02 KB
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
60
61
62
63
64
import deserialize from '../shared/deserialize'
import prefix from '../shared/prefix'
import { symbolHashJoin } from '../shared/symbolHash'
import page from './page'
import worker from './worker'
import client from './client'
export default function invoke(name, hash) {
return async function _invoke(params = {}) {
let payload
worker.fetching = true
if (Object.isFrozen(worker.queues[name])) {
worker.queues[name] = [params]
} else {
worker.queues[name] = [...worker.queues[name], params]
}
let finalHash = hash === this.hash ? hash : symbolHashJoin(hash, this.hash)
let url = `${worker.api}/${prefix}/${finalHash}/${name}.json`
if (module.hot) {
const version = client.klasses[hash].__hashes[name]
url = `${worker.api}/${prefix}/${version}/${finalHash}/${name}.json`
}
const body = JSON.stringify(params || {})
const options = {
headers: worker.headers,
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
redirect: 'follow',
referrerPolicy: 'no-referrer',
}
if (/get[A-Z]([*]*)/.test(name)) {
options.method = 'GET'
url += `?payload=${encodeURIComponent(body)}`
} else {
options.body = body
if (/patch[A-Z]([*]*)/.test(name)) {
options.method = 'PATCH'
} else if (/put[A-Z]([*]*)/.test(name)) {
options.method = 'PUT'
} else if (/delete[A-Z]([*]*)/.test(name)) {
options.method = 'DELETE'
} else {
options.method = 'POST'
}
}
try {
const response = await fetch(url, options)
page.status = response.status
const text = await response.text()
payload = deserialize(text).result
worker.responsive = true
} catch (e) {
worker.responsive = false
}
if (worker.queues[name]?.length === 1) {
delete worker.queues[name]
} else {
worker.queues[name] = worker.queues[name].filter((task) => task !== params)
}
worker.fetching = !!Object.keys(worker.queues).length
return payload
}
}