UNPKG

amesu

Version:
106 lines (105 loc) 3.06 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Request = exports.RequestError = void 0; const common_1 = require("../utils/common"); class RequestError extends Error { constructor(message) { super(message); this.name = 'RequestError'; } } exports.RequestError = RequestError; class Request { requestInterceptors; responseInterceptors; constructor() { this.requestInterceptors = []; this.responseInterceptors = []; } /** 添加请求拦截器 */ useRequestInterceptor(interceptor) { this.requestInterceptors.push(interceptor); } /** 添加响应拦截器 */ useResponseInterceptor(interceptor) { this.responseInterceptors.push(interceptor); } async basis(config) { if (typeof config.body === 'string') { const defaultConfig = { headers: { 'Content-Type': 'application/json', }, }; config = (0, common_1.deepAssign)(defaultConfig, config); } for (const interceptor of this.requestInterceptors) { config = await interceptor(config); } const url = (config.origin ?? '') + config.url; const response = await fetch(url, config); const result = { data: null, status: response.status, config, statusText: response.statusText, headers: response.headers, }; try { result.data = await response.json(); } catch (error) { if (!response.ok) { throw new RequestError((0, common_1.parseError)(error)); } result.data = await response.text(); } for (const interceptor of this.responseInterceptors) { (0, common_1.deepAssign)(result, await interceptor(result)); } return result; } get(url, params, config) { if (params) { url += (/\?/.test(url) ? '&' : '?') + (0, common_1.objectToParams)(params); } return this.basis({ url, method: 'GET', ...config, }); } delete(url, params, config = {}) { return this.basis({ url, method: 'DELETE', body: (0, common_1.parseBody)(params), ...config, }); } post(url, params, config = {}) { return this.basis({ url, method: 'POST', body: (0, common_1.parseBody)(params), ...config, }); } put(url, params, config = {}) { return this.basis({ url, method: 'PUT', body: (0, common_1.parseBody)(params), ...config, }); } patch(url, params, config = {}) { return this.basis({ url, method: 'PATCH', body: (0, common_1.parseBody)(params), ...config, }); } } exports.Request = Request;