forked from mattermost/mattermost-webapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch_etag.ts
40 lines (31 loc) · 1.32 KB
/
fetch_etag.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
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Options} from 'mattermost-redux/types/client4';
const data: {[x: string]: any} = {};
const etags: {[x: string]: string} = {};
export default ((url: string, options: Options = {headers: {}}): Promise<Response> => {
url = url || options.url || ''; // eslint-disable-line no-param-reassign
if (options.method === 'GET' || !options.method) {
const etag = etags[url!];
const cachedResponse = data[`${url}${etag}`]; // ensure etag is for url
if (etag) {
options.headers!['If-None-Match'] = etag;
}
return fetch(url!, options).
then((response) => {
if (response.status === 304) {
return cachedResponse.clone();
}
if (response.status === 200) {
const responseEtag = response.headers.get('Etag');
if (responseEtag) {
data[`${url}${responseEtag}`] = response.clone();
etags[url!] = responseEtag;
}
}
return response;
});
}
// all other requests go straight to fetch
return Reflect.apply(fetch, undefined, [url, options]);
});