forked from ava/use-http
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocalStorage.ts
64 lines (55 loc) · 1.86 KB
/
localStorage.ts
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
import { serializeResponse } from '../utils'
import { Cache } from '../types'
const cacheName = 'useHTTPcache'
const getCache = () => {
try {
return JSON.parse(localStorage.getItem(cacheName) || '{}')
} catch (err) {
localStorage.removeItem(cacheName)
return {}
}
}
const getLocalStorage = ({ cacheLife }: { cacheLife: number }): Cache => {
const remove = async (...responseIDs: string[]) => {
const cache = getCache()
responseIDs.forEach(id => delete cache[id])
localStorage.setItem(cacheName, JSON.stringify(cache))
}
const isExpired = (responseID: string) => {
const cache = getCache()
const { expiration, response } = (cache[responseID] || {})
const expired = expiration > 0 && expiration < Date.now()
if (expired) remove(responseID)
return expired || !response
}
const has = async (responseID: string) => !isExpired(responseID)
const get = async (responseID: string) => {
if (isExpired(responseID)) return
const cache = getCache()
const { body, headers, status, statusText } = cache[responseID].response
return new Response(body, {
status,
statusText,
headers: new Headers(headers || {})
})
}
const set = async (responseID: string, response: Response): Promise<void> => {
const cache = getCache()
cache[responseID] = {
response: await serializeResponse(response),
expiration: Date.now() + cacheLife
}
localStorage.setItem(cacheName, JSON.stringify(cache))
}
const clear = async () => {
localStorage.setItem(cacheName, JSON.stringify({}))
}
return Object.defineProperties(getCache(), {
get: { value: get, writable: false },
set: { value: set, writable: false },
has: { value: has, writable: false },
delete: { value: remove, writable: false },
clear: { value: clear, writable: false }
})
}
export default getLocalStorage