forked from freeCodeCamp/freeCodeCamp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch-and-cache.js
74 lines (68 loc) · 1.8 KB
/
fetch-and-cache.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
72
73
74
import { Observable } from 'rx';
import { ajax$ } from '../../common/utils/ajax-stream';
// value used to break browser ajax caching
const cacheBreakerValue = Math.random();
export function _fetchScript(
{
src,
cacheBreaker = false,
crossDomain = true
} = {},
) {
if (!src) {
throw new Error('No source provided for script');
}
if (this.cache.has(src)) {
return this.cache.get(src);
}
const url = cacheBreaker ?
`${src}?cacheBreaker=${cacheBreakerValue}` :
src;
const script = ajax$({ url, crossDomain })
.doOnNext(res => {
if (res.status !== 200) {
throw new Error('Request errror: ' + res.status);
}
})
.map(({ response }) => response)
.map(script => `<script>${script}</script>`)
.shareReplay();
this.cache.set(src, script);
return script;
}
export const fetchScript = _fetchScript.bind({ cache: new Map() });
export function _fetchLink(
{
link: href,
raw = false,
crossDomain = true
} = {},
) {
if (!href) {
return Observable.throw(new Error('No source provided for link'));
}
if (this.cache.has(href)) {
return this.cache.get(href);
}
// css files with `url(...` may not work in style tags
// so we put them in raw links
if (raw) {
const link = Observable.just(`<link href=${href} rel='stylesheet' />`)
.shareReplay();
this.cache.set(href, link);
return link;
}
const link = ajax$({ url: href, crossDomain })
.doOnNext(res => {
if (res.status !== 200) {
throw new Error('Request error: ' + res.status);
}
})
.map(({ response }) => response)
.map(script => `<style>${script}</style>`)
.catch(() => Observable.just(''))
.shareReplay();
this.cache.set(href, link);
return link;
}
export const fetchLink = _fetchLink.bind({ cache: new Map() });