From 5e4bc4b564729a76929a3d940207ff6ec54e594d Mon Sep 17 00:00:00 2001 From: Pig Fang Date: Sun, 5 Aug 2018 15:33:08 +0800 Subject: [PATCH] Use Fetch API --- resources/assets/src/js/net.js | 46 +++++++++++++++++++++++++++++++ resources/assets/src/js/notify.js | 9 +++--- resources/assets/src/shims.d.ts | 6 ++++ 3 files changed, 56 insertions(+), 5 deletions(-) diff --git a/resources/assets/src/js/net.js b/resources/assets/src/js/net.js index 2bc406ac..a60948b9 100644 --- a/resources/assets/src/js/net.js +++ b/resources/assets/src/js/net.js @@ -1,3 +1,4 @@ +import Vue from 'vue'; import axios from 'axios'; import { showAjaxError } from './notify'; @@ -8,3 +9,48 @@ axios.interceptors.response.use( response => response, showAjaxError ); + +const empty = Object.create(null); +const init = { + credentials: 'same-origin', + headers: { + 'Content-Type': 'application/json' + } +}; + +async function walkFetch(request) { + try { + const response = await fetch(request); + if (response.ok) { + return response.json(); + } else { + showAjaxError(await response.text()); + } + } catch (error) { + showAjaxError(error); + } +} + +export async function get(url, params = empty) { + const qs = Object + .keys(params) + .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`) + .join('&'); + + return walkFetch(new Request(`${blessing.base_url}${url}${qs && '?' + qs}`, init)); +} + +export async function post(url, data = empty) { + return walkFetch(new Request(`${blessing.base_url}${url}`, { + body: JSON.stringify(data), + method: 'POST', + ...init + })); +} + +Vue.use(_Vue => { + _Vue.prototype.$http = { + get, + post, + }; +}); diff --git a/resources/assets/src/js/notify.js b/resources/assets/src/js/notify.js index b70d5025..0f8316e0 100644 --- a/resources/assets/src/js/notify.js +++ b/resources/assets/src/js/notify.js @@ -20,16 +20,15 @@ export function showMsg(msg, type = 'info') { /** * Show modal if error occured when sending an ajax request. * - * @param {{ response: import('axios').AxiosResponse }} response + * @param {TypeError | string} error * @return {void} */ -export function showAjaxError({ response }) { - if (!response.data) { +export function showAjaxError(error) { + if (!error) { return console.warn('Empty Ajax response body.'); } - const message = typeof response.data === 'object' ? response.data.message : response.data; - + const message = typeof error === 'string' ? error : error.message; showModal(message.replace(/\n/g, '
'), trans('general.fatalError'), 'danger'); } diff --git a/resources/assets/src/shims.d.ts b/resources/assets/src/shims.d.ts index f8e57e3f..bd7cf216 100644 --- a/resources/assets/src/shims.d.ts +++ b/resources/assets/src/shims.d.ts @@ -17,5 +17,11 @@ declare global { declare module 'vue/types/vue' { interface Vue { $t(key: string, parameters?: object): string + + $http: { + get(url: string, params?: object) + + post(url: string, data?: object) + } } }