|
1 | 1 | import deserialize from '../shared/deserialize'; |
2 | | -import worker from './worker'; |
3 | 2 | import prefix from '../shared/prefix'; |
4 | 3 | import page from './page'; |
| 4 | +import worker from './worker'; |
5 | 5 |
|
6 | 6 | export default function invoke(name, hash) { |
7 | 7 | return async function _invoke(params = {}) { |
8 | 8 | let payload; |
9 | 9 | worker.fetching = true; |
10 | | - if(Object.isFrozen(worker.queues[name])) { |
| 10 | + if (Object.isFrozen(worker.queues[name])) { |
11 | 11 | worker.queues[name] = [params]; |
12 | 12 | } else { |
13 | 13 | worker.queues[name] = [...worker.queues[name], params]; |
14 | 14 | } |
15 | 15 | const finalHash = hash === this.constructor.hash ? hash : `${hash}-${this.constructor.hash}`; |
16 | 16 | let url = `${worker.api}/${prefix}/${finalHash}/${name}.json`; |
| 17 | + let body = JSON.stringify(params || {}); |
| 18 | + |
| 19 | + const options = { |
| 20 | + headers: worker.headers, |
| 21 | + mode: 'cors', |
| 22 | + cache: 'no-cache', |
| 23 | + credentials: 'same-origin', |
| 24 | + redirect: 'follow', |
| 25 | + referrerPolicy: 'no-referrer', |
| 26 | + } |
| 27 | + if (/get[A-Z]([*]*)/.test(name)) { |
| 28 | + options.method = 'GET'; |
| 29 | + url += `?payload=${body}`; |
| 30 | + } else { |
| 31 | + options.body = body; |
| 32 | + if (/patch[A-Z]([*]*)/.test(name)) { |
| 33 | + options.method = 'PATCH'; |
| 34 | + } else if (/put[A-Z]([*]*)/.test(name)) { |
| 35 | + options.method = 'PUT'; |
| 36 | + } else if (/delete[A-Z]([*]*)/.test(name)) { |
| 37 | + options.method = 'DELETE'; |
| 38 | + } else { |
| 39 | + options.method = 'POST'; |
| 40 | + } |
| 41 | + } |
17 | 42 | try { |
18 | | - const response = await fetch(url, { |
19 | | - method: 'POST', |
20 | | - headers: worker.headers, |
21 | | - mode: 'cors', |
22 | | - cache: 'no-cache', |
23 | | - credentials: 'same-origin', |
24 | | - redirect: 'follow', |
25 | | - referrerPolicy: 'no-referrer', |
26 | | - body: JSON.stringify(params || {}) |
27 | | - }); |
| 43 | + const response = await fetch(url, options); |
28 | 44 | page.status = response.status; |
29 | 45 | const text = await response.text(); |
30 | 46 | payload = deserialize(text).result; |
31 | 47 | worker.responsive = true; |
32 | | - } catch(e) { |
| 48 | + } catch (e) { |
33 | 49 | worker.responsive = false; |
34 | 50 | } |
35 | | - if(worker.queues[name]?.length === 1) { |
| 51 | + if (worker.queues[name]?.length === 1) { |
36 | 52 | delete worker.queues[name]; |
37 | 53 | } else { |
38 | 54 | worker.queues[name] = worker.queues[name].filter((task) => task !== params); |
|
0 commit comments