|
Line 0
Link Here
|
| 0 |
- |
1 |
//import { setError, submitting, submitted } from "../messages"; |
|
|
2 |
|
| 3 |
class HttpClient { |
| 4 |
constructor(options = {}) { |
| 5 |
this._baseURL = options.baseURL || ""; |
| 6 |
this._headers = options.headers || { |
| 7 |
"Content-Type": "application/json;charset=utf-8", |
| 8 |
}; |
| 9 |
this.csrf_token = $('meta[name="csrf-token"]').attr('content'); |
| 10 |
} |
| 11 |
|
| 12 |
async _fetchJSON( |
| 13 |
endpoint, |
| 14 |
headers = {}, |
| 15 |
options = {}, |
| 16 |
return_response = false, |
| 17 |
mark_submitting = false |
| 18 |
) { |
| 19 |
let res, error; |
| 20 |
//if (mark_submitting) submitting(); |
| 21 |
await fetch(this._baseURL + endpoint, { |
| 22 |
...options, |
| 23 |
headers: { ...this._headers, ...headers }, |
| 24 |
}) |
| 25 |
.then(response => { |
| 26 |
if (!response.ok) { |
| 27 |
return response.text().then(text => { |
| 28 |
let message; |
| 29 |
if (text) { |
| 30 |
let json = JSON.parse(text); |
| 31 |
message = |
| 32 |
json.error || |
| 33 |
json.errors.map(e => e.message).join("\n") || |
| 34 |
json; |
| 35 |
} else { |
| 36 |
message = response.statusText; |
| 37 |
} |
| 38 |
throw new Error(message); |
| 39 |
}); |
| 40 |
} |
| 41 |
return return_response ? response : response.json(); |
| 42 |
}) |
| 43 |
.then(result => { |
| 44 |
res = result; |
| 45 |
}) |
| 46 |
.catch(err => { |
| 47 |
error = err; |
| 48 |
//setError(err); |
| 49 |
console.error(err); |
| 50 |
}) |
| 51 |
.then(() => { |
| 52 |
//if (mark_submitting) submitted(); |
| 53 |
}); |
| 54 |
|
| 55 |
if (error) throw Error(error); |
| 56 |
|
| 57 |
return res; |
| 58 |
} |
| 59 |
|
| 60 |
post(params = {}) { |
| 61 |
const body = params.body |
| 62 |
? typeof params.body === "string" |
| 63 |
? params.body |
| 64 |
: JSON.stringify(params.body) |
| 65 |
: params.data || undefined; |
| 66 |
let csrf_token = { csrf_token: this.csrf_token }; |
| 67 |
let headers = { ...csrf_token, ...params.headers }; |
| 68 |
return this._fetchJSON( |
| 69 |
params.endpoint, |
| 70 |
headers, |
| 71 |
{ |
| 72 |
...params.options, |
| 73 |
body, |
| 74 |
method: "POST", |
| 75 |
}, |
| 76 |
false, |
| 77 |
true |
| 78 |
); |
| 79 |
} |
| 80 |
|
| 81 |
} |
| 82 |
|
| 83 |
export default HttpClient; |