forked from nullstack/nullstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvoke.js
More file actions
58 lines (57 loc) · 1.78 KB
/
invoke.js
File metadata and controls
58 lines (57 loc) · 1.78 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
import deserialize from '../shared/deserialize';
import prefix from '../shared/prefix';
import page from './page';
import worker from './worker';
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];
}
const finalHash = hash === this.hash ? hash : `${hash}-${this.hash}`;
let url = `${worker.api}/${prefix}/${finalHash}/${name}.json`;
let 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=${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;
}
}