-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathindex.js
50 lines (45 loc) · 1.3 KB
/
index.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
var usePromise = require('./usePromise')
function UseFetchError (status, statusText, message, fileName, lineNumber) {
var instance = new Error(message, fileName, lineNumber)
instance.name = 'UseFetchError'
instance.status = status
instance.statusText = statusText
Object.setPrototypeOf(instance, Object.getPrototypeOf(this))
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, UseFetchError)
}
return instance
}
UseFetchError.prototype = Object.create(Error.prototype, {
constructor: {
value: Error,
enumerable: false,
writable: true,
configurable: true
}
})
Object.setPrototypeOf(UseFetchError, Error)
function useFetch (
path,
options,
specialOptions
) {
var blocked = ((specialOptions && specialOptions.depends) ||
(options && options.depends) || [])
.reduce(function (acc, dep) { return acc || !dep }, false)
return usePromise(!blocked && function (p, o, s) {
return fetch(p, o)
.then((s && s.formatter) || (o && o.formatter) || function (response) {
if (!response.ok) {
throw new UseFetchError(
response.status,
response.statusText,
'Fetch error'
)
}
return response.json()
})
},
path, options || {}, specialOptions || {})
}
module.exports = useFetch