UNPKG

1.55 kBJavaScriptView Raw
1var debug = require('debug')('httpism:cache')
2var fileStore = require('./fileStore')
3var urlUtils = require('url')
4
5function createStore (options) {
6 var url = typeof options === 'object' && options.hasOwnProperty('url') ? options.url : undefined
7 var parsedUrl = urlUtils.parse(url)
8 var protocol = parsedUrl.protocol || 'file'
9
10 var storeConstructor = storeTypes[protocol]
11
12 if (!storeConstructor) {
13 throw new Error('no such store for url: ' + url)
14 }
15
16 return storeConstructor(options)
17}
18
19module.exports = function (options) {
20 var store = createStore(options)
21 var isResponseCachable = typeof options === 'object' &&
22 options.hasOwnProperty('isResponseCachable')
23 ? options.isResponseCachable
24 : function (response) {
25 return response.statusCode >= 200 && response.statusCode < 400
26 }
27
28 var httpismCache = function (req, next) {
29 var url = req.url
30
31 return store.responseExists(url).then(function (exists) {
32 if (exists) {
33 debug('hit', url)
34 return store.readResponse(url)
35 } else {
36 debug('miss', url)
37 return next().then(function (response) {
38 if (isResponseCachable(response)) {
39 return store.writeResponse(url, response)
40 } else {
41 return response
42 }
43 })
44 }
45 })
46 }
47
48 httpismCache.httpismMiddleware = {
49 name: 'cache',
50 before: ['debugLog', 'http']
51 }
52
53 httpismCache.middleware = 'cache'
54 httpismCache.before = ['debugLog', 'http']
55
56 return httpismCache
57}
58
59var storeTypes = {
60 file: fileStore
61}