|
| 1 | +// @flow |
| 2 | +/* globals Request, Response, Headers */ |
| 3 | + |
| 4 | +import {AsyncStorage} from 'react-native' |
| 5 | +import CachePolicy from 'http-cache-semantics' |
| 6 | +import fromPairs from 'lodash/fromPairs' |
| 7 | + |
| 8 | +const ROOT = 'fp' |
| 9 | +const debug = false |
| 10 | + |
| 11 | +// Pulls out the important bits from a Request for storage |
| 12 | +async function serializeResponse(r: Request) { |
| 13 | + let {headers, status, statusText} = r |
| 14 | + let body = await r.clone().text() |
| 15 | + if ('entries' in headers) { |
| 16 | + headers = [...headers.entries()] |
| 17 | + } |
| 18 | + return {headers, status, statusText, body} |
| 19 | +} |
| 20 | + |
| 21 | +// Converts a whatwg Headers instance into a plain object for http-cache-semantics |
| 22 | +function headersInstanceToObject(headers: Headers) { |
| 23 | + return fromPairs([...Object.entries(headers)]) |
| 24 | +} |
| 25 | + |
| 26 | +// Converts a whatwg Response into a plain object for http-cache-semantics |
| 27 | +function responseForCachePolicy({url, method, headers}: Response) { |
| 28 | + // Response must have a headers property with all header names in lower |
| 29 | + // case. `url` and `method` are optional. |
| 30 | + |
| 31 | + return {url, method, headers: headersInstanceToObject(headers)} |
| 32 | +} |
| 33 | + |
| 34 | +// Converts a whatwg Request into a plain object for http-cache-semantics |
| 35 | +function requestForCachePolicy({status, headers}: Request) { |
| 36 | + // Request must have a headers property with all header names in lower |
| 37 | + // case. `url` and `status` are optional. |
| 38 | + |
| 39 | + return {status, headers: headersInstanceToObject(headers)} |
| 40 | +} |
| 41 | + |
| 42 | +export async function insertForUrl(url: string, data: mixed) { |
| 43 | + let key = `urlcache:${url}` |
| 44 | + |
| 45 | + let {policy: oldPolicy} = await getItem(key) |
| 46 | + |
| 47 | + if (oldPolicy) { |
| 48 | + return |
| 49 | + } |
| 50 | + |
| 51 | + let req = new Request(url) |
| 52 | + let resp = new Response(JSON.stringify(data), {status: 200}) |
| 53 | + let policy = new CachePolicy( |
| 54 | + requestForCachePolicy(req), |
| 55 | + responseForCachePolicy(resp), |
| 56 | + ) |
| 57 | + |
| 58 | + return cacheItem({key, response: resp, policy}) |
| 59 | +} |
| 60 | + |
| 61 | +// Does the magic: stores a Request into AsyncStorage |
| 62 | +type CacheItemArgs = {key: string, response: Response, policy: CachePolicy} |
| 63 | +async function cacheItem({key, response, policy}: CacheItemArgs) { |
| 64 | + response = await serializeResponse(response) |
| 65 | + |
| 66 | + await AsyncStorage.multiSet([ |
| 67 | + [`${ROOT}:${key}:response`, JSON.stringify(response)], |
| 68 | + [`${ROOT}:${key}:policy`, JSON.stringify(policy.toObject())], |
| 69 | + [`${ROOT}:${key}:ttl`, JSON.stringify(policy.timeToLive())], |
| 70 | + ]) |
| 71 | +} |
| 72 | + |
| 73 | +// Does more magic: gets a Request from AsyncStorage |
| 74 | +type GetItemResult = {response: Response, policy: ?CachePolicy} |
| 75 | +async function getItem(key: string): Promise<GetItemResult> { |
| 76 | + let [[, response], [, policy]] = await AsyncStorage.multiGet([ |
| 77 | + `${ROOT}:${key}:response`, |
| 78 | + `${ROOT}:${key}:policy`, |
| 79 | + ]) |
| 80 | + |
| 81 | + if (!response) { |
| 82 | + return {response, policy: null} |
| 83 | + } |
| 84 | + |
| 85 | + let {body, ...init} = JSON.parse(response) |
| 86 | + |
| 87 | + return { |
| 88 | + response: new Response(body, init), |
| 89 | + policy: CachePolicy.fromObject(JSON.parse(policy)), |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +// Requests an URL and retrieves it from the cache if possible |
| 94 | +export async function cachedFetch(request: Request): Promise<Response> { |
| 95 | + let {url} = request |
| 96 | + |
| 97 | + let cachePolicyRequest = requestForCachePolicy(request) |
| 98 | + |
| 99 | + let key = `urlcache:${url}` |
| 100 | + let {response: oldResponse, policy: oldPolicy} = await getItem(key) |
| 101 | + |
| 102 | + // If nothing has ever been cached, go fetch it |
| 103 | + if (!oldPolicy) { |
| 104 | + debug && console.log(`fetch(${request.url}): no policy cached; fetching`) |
| 105 | + |
| 106 | + let response = await fetch(request) |
| 107 | + let cachePolicyResponse = responseForCachePolicy(response) |
| 108 | + |
| 109 | + let policy = new CachePolicy(cachePolicyRequest, cachePolicyResponse) |
| 110 | + |
| 111 | + if (policy.storable()) { |
| 112 | + debug && console.log(`fetch(${request.url}): caching`) |
| 113 | + await cacheItem({key, response, policy}) |
| 114 | + } else { |
| 115 | + debug && console.log(`fetch(${request.url}): not cachable`) |
| 116 | + } |
| 117 | + |
| 118 | + return response |
| 119 | + } |
| 120 | + |
| 121 | + // If we can re-use the cached data, return it; otherwise, we're serving requests from the cache |
| 122 | + if (oldPolicy.satisfiesWithoutRevalidation(cachePolicyRequest)) { |
| 123 | + debug && console.log(`fetch(${request.url}): fresh; returning`) |
| 124 | + oldResponse.headers = new Headers(oldPolicy.responseHeaders()) |
| 125 | + return oldResponse |
| 126 | + } |
| 127 | + |
| 128 | + // Update the request to ask the origin server if the cached response can be used |
| 129 | + request.headers = new Headers( |
| 130 | + oldPolicy.revalidationHeaders(cachePolicyRequest), |
| 131 | + ) |
| 132 | + |
| 133 | + debug && console.log(`fetch(${request.url}): stale; validating`) |
| 134 | + |
| 135 | + // Send request to the origin server. The server may respond with status 304 |
| 136 | + let newResponse = await fetch(request) |
| 137 | + let newCachePolicyResponse = responseForCachePolicy(newResponse) |
| 138 | + |
| 139 | + // Create updated policy and combined response from the old and new data |
| 140 | + let {policy, modified} = oldPolicy.revalidatedPolicy( |
| 141 | + cachePolicyRequest, |
| 142 | + newCachePolicyResponse, |
| 143 | + ) |
| 144 | + |
| 145 | + if (debug) { |
| 146 | + if (modified) { |
| 147 | + console.log(`fetch(${request.url}): validated; did change`) |
| 148 | + } else { |
| 149 | + console.log(`fetch(${request.url}): validated; 304 no change`) |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + let response = modified ? newResponse : oldResponse |
| 154 | + |
| 155 | + // Update the cache with the newer/fresher response |
| 156 | + await cacheItem({key, policy, response}) |
| 157 | + |
| 158 | + // And proceed returning cached response as usual |
| 159 | + response.headers = new Headers(policy.responseHeaders()) |
| 160 | + |
| 161 | + debug && console.log(`fetch(${request.url}): returning updated response`) |
| 162 | + |
| 163 | + return response |
| 164 | +} |
0 commit comments