From ea98dbcc4c3a9bfc0bf6de452e0da826276ff29c Mon Sep 17 00:00:00 2001 From: inkss Date: Thu, 2 Jun 2022 21:01:20 +0800 Subject: [PATCH] feat(VolantisRequest): Fetch, POST, Get --- source/js/app.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/source/js/app.js b/source/js/app.js index c56ccef68..dd530cc58 100755 --- a/source/js/app.js +++ b/source/js/app.js @@ -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);