-
Notifications
You must be signed in to change notification settings - Fork 2
/
cache.js
70 lines (58 loc) · 1.71 KB
/
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
var debug = require('debug')('httpism:cache')
var fileStore = require('./fileStore')
var URL = require('url').URL
var pathUtils = require('path')
function urlProtocol (url) {
if (pathUtils.isAbsolute(url)) {
return 'file'
} else {
var parsedUrl = new URL(url)
return parsedUrl.protocol || 'file'
}
}
function createStore (options) {
var url = typeof options === 'object' && Object.prototype.hasOwnProperty.call(options, 'url') ? options.url : undefined
var protocol = urlProtocol(url)
var storeConstructor = storeTypes[protocol]
if (!storeConstructor) {
throw new Error('no such store for url: ' + url)
}
return storeConstructor(options)
}
module.exports = function (options) {
var store = createStore(options)
var isResponseCachable = typeof options === 'object' &&
Object.prototype.hasOwnProperty.call(options, 'isResponseCachable')
? options.isResponseCachable
: function (response) {
return response.statusCode >= 200 && response.statusCode < 400
}
var httpismCache = function (req, next) {
var url = req.url
return store.responseExists(url).then(function (exists) {
if (exists) {
debug('hit', url)
return store.readResponse(url)
} else {
debug('miss', url)
return next().then(function (response) {
if (isResponseCachable(response)) {
return store.writeResponse(url, response)
} else {
return response
}
})
}
})
}
httpismCache.httpismMiddleware = {
name: 'cache',
before: ['debugLog', 'http']
}
httpismCache.middleware = 'cache'
httpismCache.before = ['debugLog', 'http']
return httpismCache
}
var storeTypes = {
file: fileStore
}