Skip to content

Commit

Permalink
feat(VolantisRequest): Fetch, POST, Get
Browse files Browse the repository at this point in the history
  • Loading branch information
inkss authored Jun 2, 2022
1 parent be4cf3f commit ea98dbc
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions source/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -1126,3 +1126,47 @@ const DOMController = {
}
}
Object.freeze(DOMController);

const VolantisRequest = {
timeoutFetch: (url, ms, requestInit) => {
const controller = new AbortController()
requestInit.signal?.addEventListener('abort', () => controller.abort())
let promise = fetch(url, { ...requestInit, signal: controller.signal })
if (ms > 0) {
const timer = setTimeout(() => controller.abort(), ms)
promise.finally(() => { clearTimeout(timer) })
}
promise = promise.catch((err) => {
throw ((err || {}).name === 'AbortError') ? new Error(`Fetch timeout: ${url}`) : err
})
return promise
},

Fetch: async (url, requestInit, timeout = 15000) => {
const resp = await VolantisRequest.timeoutFetch(url, timeout, requestInit);
if (!resp.ok) throw new Error(`Fetch error: ${url} | ${resp.status}`);
let json = await resp.json()
if (!json.success) throw json
return json
},

POST: async (url, data) => {
const requestInit = {
method: 'POST',
}
if (data) {
const formData = new FormData();
Object.keys(data).forEach(key => formData.append(key, String(data[key])))
requestInit.body = formData;
}
const json = await VolantisRequest.Fetch(url, requestInit)
return json.data;
},

Get: async (url, data) => {
const json = await VolantisRequest.Fetch(url + (data ? (`?${new URLSearchParams(data)}`) : ''), {
method: 'GET'
})
}
}
Object.freeze(VolantisRequest);

0 comments on commit ea98dbc

Please sign in to comment.