Fetch封装

743 阅读1分钟

Fetch封装

const baseUrl = 'url地址'

//参数转换
const queryString = params => '?' + Object
	.keys(params)
	.map(key => `${key}=${encodeURIComponent(params[key])}`)
	.join('&');

const request = (partialUrl, body, query, method = 'GET', mode = 'cors', contentType = 'application/x-www-form-urlencoded') => {
	const needContentType = ['POST', 'PUT', 'GET'].includes(method.toUpperCase());
	const url = baseUrl + partialUrl + (query ? queryString(query) : '');
	return new Promise((success, fail) => fetch(url, {
		method, //请求方式
		mode,   //跨域模式
		data: body, //请求参数
		headers: {  //请求头
			...needContentType ? {
				'Content-Type': contentType
			} : {}
		}
	}).then(response => {
		success(response.json());
		fail(response);
	}))
}

class Fetch {
	constructor(before, after) {
		this.before = before; //请求前拦截器
		this.after = after; //请求后拦截器
	}

	_request(partialUrl, body, query, method, mode, contentType) {
		this.before && this.before();	// 执行请求前拦截器。
		const promise = request(partialUrl, body, query, method, mode, contentType);
		promise.finally(() => this.after && this.after()); // 执行请求后拦截器。
		return promise;
	}

	get(partialUrl, query, contentType) {

		return this._request(partialUrl, undefined, query, "GET", undefined, contentType);
	}

	delete(partialUrl, query) {
		return this._request(partialUrl, undefined, query, undefined, 'DELETE');
	}

	post(partialUrl, body, query, contentType) {
		return this._request(partialUrl, body, query, 'POST', undefined, contentType)
	}

	put(partialUrl, body, query, contentType) {
		return this._request(partialUrl, body, query, 'PUT', undefined, contentType)
	}

}

const FetchApi = {
	get: (partialUrl, query, contentType) => {
		return new Fetch().get(partialUrl, undefined, query, contentType);
	},
	delete: (partialUrl, query) => {
		return new Fetch().delete(partialUrl, undefined, query);
	},
	post: (partialUrl, body, query, contentType) => {
		return new Fetch().post(partialUrl, body, query, contentType);
	},
	put: (partialUrl, body, query, contentType) => {
		return new Fetch().put(partialUrl, body, query, contentType);
	}
}

export default FetchApi;