1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | function getCacheExpiry(xhr){
|
9 | var expiresHeader = xhr.getResponseHeader('Expires');
|
10 | var cacheControlHeader = xhr.getResponseHeader('Cache-Control');
|
11 |
|
12 | var expiry = parseCacheControlHeader(cacheControlHeader);
|
13 | if(expiry === undefined) {
|
14 | expiry = parseExpiresHeader(expiresHeader);
|
15 | }
|
16 | expiry = nullifyInvalidExpiration(expiry);
|
17 | return expiry;
|
18 | }
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | function parseCacheControlHeader(cacheControlHeader){
|
27 | if(cacheControlHeader === null){
|
28 | return undefined;
|
29 | }
|
30 | var headerData = cacheControlHeader.split(",");
|
31 | var expiry = undefined;
|
32 | var keyword;
|
33 | for(var i=0; i<headerData.length; i++){
|
34 | keyword = headerData[i].trim();
|
35 | if(keyword.indexOf("max-age") > -1){
|
36 | expiry = parseCacheControlAge(keyword, expiry);
|
37 | }else{
|
38 | expiry = parseCacheControlKeyword(keyword, expiry);
|
39 | }
|
40 | }
|
41 | return expiry;
|
42 | }
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 | function parseCacheControlAge(maxAge, expiry){
|
50 | if(expiry === null){
|
51 | return expiry;
|
52 | }
|
53 | var seconds = maxAge.split('=')[1].trim();
|
54 | seconds = parseInt(seconds);
|
55 | if(isNaN(seconds)){
|
56 | return undefined;
|
57 | }else{
|
58 | return nowPlusSeconds(seconds);
|
59 | }
|
60 | }
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 | function parseCacheControlKeyword(keyword, expiry){
|
67 | if(keyword.indexOf("public") > -1 || keyword.indexOf("private") > -1){
|
68 | return expiry;
|
69 | }
|
70 | if(keyword.indexOf("no-cache") > -1 || keyword.indexOf("no-store") > -1){
|
71 | return null;
|
72 | }
|
73 | if(keyword.indexOf("must-revalidate") > -1 || keyword.indexOf("proxy-revalidate") > -1){
|
74 | return expiry;
|
75 | }
|
76 | if(keyword.indexOf("s-maxage") > -1){
|
77 | return expiry;
|
78 | }
|
79 | return expiry;
|
80 | }
|
81 |
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 |
|
88 | function parseExpiresHeader(expiresHeader){
|
89 | if(expiresHeader === null) {
|
90 | return undefined;
|
91 | }
|
92 | expires = new Date(expiresHeader);
|
93 | if(expires == "Invalid Date"){
|
94 | return null;
|
95 | }
|
96 | return expires;
|
97 | }
|
98 |
|
99 |
|
100 |
|
101 |
|
102 | function nullifyInvalidExpiration(expiration){
|
103 | if(expiration instanceof Date && expiration < new Date()){
|
104 | return null;
|
105 | }
|
106 | return expiration;
|
107 | }
|
108 |
|
109 |
|
110 |
|
111 |
|
112 | function nowPlusSeconds(seconds){
|
113 | var now = new Date();
|
114 | now.setTime(now.getTime() + seconds * 1000);
|
115 | return now;
|
116 | }
|
117 |
|
118 | module.exports.getCacheExpiry = getCacheExpiry;
|
119 | module.exports.nowPlusSeconds = nowPlusSeconds;
|