1 | import handleError from '/static/js/handleError.js'
|
2 |
|
3 | const parse = async res => {
|
4 | const body = await res.text()
|
5 | try {
|
6 | return JSON.parse(body)
|
7 | } catch (err) {
|
8 | alert('Error while parsing JSON\n' + body)
|
9 | }
|
10 | }
|
11 |
|
12 | export default function fetchJSON (url, method, data) {
|
13 | if (!method) {
|
14 | return fetch(url).then(parse).catch(handleError)
|
15 | }
|
16 |
|
17 | if (typeof method !== 'string') {
|
18 | data = method
|
19 |
|
20 | return fetch(url, {
|
21 | method: 'POST',
|
22 | headers: {
|
23 | 'Content-Type': 'application/json'
|
24 | },
|
25 | body: JSON.stringify(data)
|
26 | }).then(parse).catch(handleError)
|
27 | }
|
28 |
|
29 | return fetch(url, {
|
30 | method,
|
31 | headers: {
|
32 | 'Content-Type': 'application/json'
|
33 | },
|
34 | body: JSON.stringify(data != null ? data : {})
|
35 | }).then(parse).catch(handleError)
|
36 | }
|