-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch.js
71 lines (61 loc) · 1.7 KB
/
fetch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// fetch usage: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
// fetch可以接收一个参数或两个参数 fetch(url/Request,[options]), 此处只考虑fetch(url,options) 的情况
// https://github.com/sindresorhus/is-plain-obj
function isPlainObject(value) {
if (Object.prototype.toString.call(value) !== '[object Object]') {
return false
}
const prototype = Object.getPrototypeOf(value)
return prototype === null || prototype === Object.prototype
}
const { fetch } = window
function fetchApi(url, options) {
return fetch(url, options)
}
// redux中间件模式
const applyMiddleware = (func, middlewares) =>
middlewares.reduce((prev, cur) => cur(prev), func)
/**
* 1. 添加'Content-Type': 'application/json'
* 2. 将body stringify
* @param {*} next
* @returns
*/
const reqToJson = next => (url, options) => {
let { body, headers } = options
if (isPlainObject(body)) {
body = JSON.stringify(body)
} else {
throw new Error('options.body is not plainObject')
}
if (!headers) {
headers = {}
}
if (!headers['Content-Type']) {
headers = {
...headers,
'Content-Type': 'application/json',
}
} else {
throw new Error(
'headers with Content-Type is already set, and it\'s not "application/json"'
)
}
return next(url, { ...options, headers, body })
}
/**
* 为url添加前缀
* @param {*} baseUrl
* @returns
*/
const addPrefix = baseUrl => next => (url, options) => {
if (typeof baseUrl !== 'string') {
throw new Error('baseUrl should be string')
}
return next(`${baseUrl}${url}`, options)
}
const myFetch = applyMiddleware(fetchApi, [
reqToJson,
addPrefix('http://localhost:3001'),
])
export default myFetch