cacheable-request 7.0.1 → 8.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +2 -1
  2. package/README.md +11 -10
  3. package/package.json +22 -21
  4. package/src/index.js +83 -86
package/LICENSE CHANGED
@@ -1,6 +1,7 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2017 Luke Childs
3
+ Copyright (c) 2017-2021 Luke Childs
4
+ Copyright (c) 2022 Jared Wray
4
5
 
5
6
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
7
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  > Wrap native HTTP requests with RFC compliant cache support
4
4
 
5
- [![Build Status](https://travis-ci.org/lukechilds/cacheable-request.svg?branch=master)](https://travis-ci.org/lukechilds/cacheable-request)
6
- [![Coverage Status](https://coveralls.io/repos/github/lukechilds/cacheable-request/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/cacheable-request?branch=master)
5
+ [![tests](https://github.com/jaredwray/cacheable-request/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/cacheable-request/actions/workflows/tests.yaml)
6
+ [![codecov](https://codecov.io/gh/jaredwray/cacheable-request/branch/master/graph/badge.svg?token=LDLaqe4PsI)](https://codecov.io/gh/jaredwray/cacheable-request)
7
7
  [![npm](https://img.shields.io/npm/dm/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request)
8
8
  [![npm](https://img.shields.io/npm/v/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request)
9
9
 
@@ -20,7 +20,7 @@
20
20
  - Updates `Age` header on cached responses
21
21
  - Can completely bypass cache on a per request basis
22
22
  - In memory cache by default
23
- - Official support for Redis, MongoDB, SQLite, PostgreSQL and MySQL storage adapters
23
+ - Official support for Redis, Memcache, Etcd, MongoDB, SQLite, PostgreSQL and MySQL storage adapters
24
24
  - Easily plug in your own or third-party storage adapters
25
25
  - If DB connection fails, cache is automatically bypassed ([disabled by default](#optsautomaticfailover))
26
26
  - Adds cache support to any existing HTTP code with minimal changes
@@ -35,8 +35,8 @@ npm install cacheable-request
35
35
  ## Usage
36
36
 
37
37
  ```js
38
- const http = require('http');
39
- const CacheableRequest = require('cacheable-request');
38
+ import http from 'http';
39
+ import CacheableRequest from 'cacheable-request';
40
40
 
41
41
  // Then instead of
42
42
  const req = http.request('http://example.com', cb);
@@ -55,7 +55,7 @@ const cacheableRequest = new CacheableRequest(electron.net);
55
55
 
56
56
  ## Storage Adapters
57
57
 
58
- `cacheable-request` uses [Keyv](https://github.com/lukechilds/keyv) to support a wide range of storage adapters.
58
+ `cacheable-request` uses [Keyv](https://github.com/jaredwray/keyv) to support a wide range of storage adapters.
59
59
 
60
60
  For example, to use Redis as a cache backend, you just need to install the official Redis Keyv storage adapter:
61
61
 
@@ -69,7 +69,7 @@ And then you can pass `CacheableRequest` your connection string:
69
69
  const cacheableRequest = new CacheableRequest(http.request, 'redis://user:pass@localhost:6379');
70
70
  ```
71
71
 
72
- [View all official Keyv storage adapters.](https://github.com/lukechilds/keyv#official-storage-adapters)
72
+ [View all official Keyv storage adapters.](https://github.com/jaredwray/keyv#official-storage-adapters)
73
73
 
74
74
  Keyv also supports anything that follows the Map API so it's easy to write your own storage adapter or use a third-party solution.
75
75
 
@@ -86,7 +86,7 @@ const storageAdapter = new QuickLRU({ maxSize: 1000 });
86
86
  const cacheableRequest = new CacheableRequest(http.request, storageAdapter);
87
87
  ```
88
88
 
89
- View the [Keyv docs](https://github.com/lukechilds/keyv) for more information on how to use storage adapters.
89
+ View the [Keyv docs](https://github.com/jaredwray/keyv) for more information on how to use storage adapters.
90
90
 
91
91
  ## API
92
92
 
@@ -105,7 +105,7 @@ Request function to wrap with cache support. Should be [`http.request`](https://
105
105
  Type: `Keyv storage adapter`<br>
106
106
  Default: `new Map()`
107
107
 
108
- A [Keyv](https://github.com/lukechilds/keyv) storage adapter instance, or connection string if using with an official Keyv storage adapter.
108
+ A [Keyv](https://github.com/jaredwray/keyv) storage adapter instance, or connection string if using with an official Keyv storage adapter.
109
109
 
110
110
  ### Instance
111
111
 
@@ -203,4 +203,5 @@ cacheableRequest('example.com', cb)
203
203
 
204
204
  ## License
205
205
 
206
- MIT © Luke Childs
206
+ MIT © Luke Childs 2017-2021
207
+ MIT © Jared Wray 2022
package/package.json CHANGED
@@ -1,17 +1,19 @@
1
1
  {
2
2
  "name": "cacheable-request",
3
- "version": "7.0.1",
3
+ "version": "8.0.1",
4
4
  "description": "Wrap native HTTP requests with RFC compliant cache support",
5
5
  "license": "MIT",
6
- "repository": "lukechilds/cacheable-request",
7
- "author": "Luke Childs <lukechilds123@gmail.com> (http://lukechilds.co.uk)",
6
+ "repository": "jaredwray/cacheable-request",
7
+ "author": "Jared Wray <me@jaredwray.com> (http://jaredwray.com)",
8
+ "type": "module",
8
9
  "main": "src/index.js",
9
10
  "engines": {
10
- "node": ">=8"
11
+ "node": ">=14"
11
12
  },
12
13
  "scripts": {
13
14
  "test": "xo && nyc ava",
14
- "coverage": "nyc report --reporter=text-lcov | coveralls"
15
+ "coverage": "nyc report --reporter=text-lcov > coverage.lcov",
16
+ "clean": "rm -rf node_modules && rm -rf .nyc_output && rm -rf coverage.lcov && rm -rf ./test/testdb.sqlite"
15
17
  },
16
18
  "files": [
17
19
  "src"
@@ -30,25 +32,24 @@
30
32
  ],
31
33
  "dependencies": {
32
34
  "clone-response": "^1.0.2",
33
- "get-stream": "^5.1.0",
34
- "http-cache-semantics": "^4.0.0",
35
- "keyv": "^4.0.0",
36
- "lowercase-keys": "^2.0.0",
37
- "normalize-url": "^4.1.0",
35
+ "get-stream": "^6.0.1",
36
+ "http-cache-semantics": "^4.1.0",
37
+ "keyv": "^4.3.0",
38
+ "normalize-url": "^7.0.3",
38
39
  "responselike": "^2.0.0"
39
40
  },
40
41
  "devDependencies": {
41
- "@keyv/sqlite": "^2.0.0",
42
- "ava": "^1.1.0",
43
- "coveralls": "^3.0.0",
44
- "create-test-server": "3.0.0",
45
- "delay": "^4.0.0",
46
- "eslint-config-xo-lukechilds": "^1.0.0",
47
- "nyc": "^14.1.1",
48
- "pify": "^4.0.0",
49
- "sqlite3": "^4.0.2",
50
- "this": "^1.0.2",
51
- "xo": "^0.23.0"
42
+ "@babel/core": "^7.18.2",
43
+ "@babel/register": "^7.17.7",
44
+ "@keyv/sqlite": "^3.5.2",
45
+ "ava": "^4.3.0",
46
+ "create-test-server": "3.0.1",
47
+ "delay": "^5.0.0",
48
+ "eslint-config-xo-lukechilds": "^1.0.1",
49
+ "nyc": "^15.1.0",
50
+ "pify": "^6.0.0",
51
+ "sqlite3": "^5.0.8",
52
+ "xo": "^0.50.0"
52
53
  },
53
54
  "xo": {
54
55
  "extends": "xo-lukechilds"
package/src/index.js CHANGED
@@ -1,76 +1,88 @@
1
- 'use strict';
2
-
3
- const EventEmitter = require('events');
4
- const urlLib = require('url');
5
- const normalizeUrl = require('normalize-url');
6
- const getStream = require('get-stream');
7
- const CachePolicy = require('http-cache-semantics');
8
- const Response = require('responselike');
9
- const lowercaseKeys = require('lowercase-keys');
10
- const cloneResponse = require('clone-response');
11
- const Keyv = require('keyv');
12
-
1
+ import EventEmitter from 'node:events';
2
+ import urlLib from 'node:url';
3
+ import crypto from 'node:crypto';
4
+ import stream from 'node:stream';
5
+ import normalizeUrl from 'normalize-url';
6
+ import getStream from 'get-stream';
7
+ import CachePolicy from 'http-cache-semantics';
8
+ import Response from 'responselike';
9
+ import cloneResponse from 'clone-response';
10
+ import Keyv from 'keyv';
11
+
12
+ const { Readable } = stream;
13
13
  class CacheableRequest {
14
14
  constructor(request, cacheAdapter) {
15
15
  if (typeof request !== 'function') {
16
16
  throw new TypeError('Parameter `request` must be a function');
17
17
  }
18
18
 
19
- this.cache = new Keyv({
20
- uri: typeof cacheAdapter === 'string' && cacheAdapter,
21
- store: typeof cacheAdapter !== 'string' && cacheAdapter,
22
- namespace: 'cacheable-request'
23
- });
19
+ if (cacheAdapter instanceof Keyv) {
20
+ this.cache = cacheAdapter;
21
+ } else {
22
+ this.cache = new Keyv({
23
+ uri: typeof cacheAdapter === 'string' && cacheAdapter,
24
+ store: typeof cacheAdapter !== 'string' && cacheAdapter,
25
+ namespace: 'cacheable-request',
26
+ });
27
+ }
24
28
 
25
- return this.createCacheableRequest(request);
29
+ return this.createCacheableRequest(request); // eslint-disable-line no-constructor-return
26
30
  }
27
31
 
28
32
  createCacheableRequest(request) {
29
- return (opts, cb) => {
33
+ return (options, cb) => {
30
34
  let url;
31
- if (typeof opts === 'string') {
32
- url = normalizeUrlObject(urlLib.parse(opts));
33
- opts = {};
34
- } else if (opts instanceof urlLib.URL) {
35
- url = normalizeUrlObject(urlLib.parse(opts.toString()));
36
- opts = {};
35
+ if (typeof options === 'string') {
36
+ url = normalizeUrlObject(urlLib.parse(options));
37
+ options = {};
38
+ } else if (options instanceof urlLib.URL) {
39
+ url = normalizeUrlObject(urlLib.parse(options.toString()));
40
+ options = {};
37
41
  } else {
38
- const [pathname, ...searchParts] = (opts.path || '').split('?');
39
- const search = searchParts.length > 0 ?
40
- `?${searchParts.join('?')}` :
41
- '';
42
- url = normalizeUrlObject({ ...opts, pathname, search });
42
+ const [pathname, ...searchParts] = (options.path || '').split('?');
43
+ const search = searchParts.length > 0
44
+ ? `?${searchParts.join('?')}`
45
+ : '';
46
+ url = normalizeUrlObject({ ...options, pathname, search });
43
47
  }
44
48
 
45
- opts = {
49
+ options = {
46
50
  headers: {},
47
51
  method: 'GET',
48
52
  cache: true,
49
53
  strictTtl: false,
50
54
  automaticFailover: false,
51
- ...opts,
52
- ...urlObjectToRequestOptions(url)
55
+ ...options,
56
+ ...urlObjectToRequestOptions(url),
53
57
  };
54
- opts.headers = lowercaseKeys(opts.headers);
55
-
58
+ options.headers = Object.fromEntries(Object.entries(options.headers).map(([key, value]) => [key.toLowerCase(), value]));
56
59
  const ee = new EventEmitter();
57
- const normalizedUrlString = normalizeUrl(
58
- urlLib.format(url),
59
- {
60
- stripWWW: false,
61
- removeTrailingSlash: false,
62
- stripAuthentication: false
60
+ const normalizedUrlString = normalizeUrl(urlLib.format(url), {
61
+ stripWWW: false,
62
+ removeTrailingSlash: false,
63
+ stripAuthentication: false,
64
+ });
65
+ let key = `${options.method}:${normalizedUrlString}`;
66
+ // POST, PATCH, and PUT requests may be cached, depending on the response
67
+ // cache-control headers. As a result, the body of the request should be
68
+ // added to the cache key in order to avoid collisions.
69
+ if (options.body && ['POST', 'PATCH', 'PUT'].includes(options.method)) {
70
+ if (options.body instanceof Readable) {
71
+ // Streamed bodies should completely skip the cache because they may
72
+ // or may not be hashable and in either case the stream would need to
73
+ // close before the cache key could be generated.
74
+ options.cache = false;
75
+ } else {
76
+ key += `:${crypto.createHash('md5').update(options.body).digest('hex')}`;
63
77
  }
64
- );
65
- const key = `${opts.method}:${normalizedUrlString}`;
78
+ }
79
+
66
80
  let revalidate = false;
67
81
  let madeRequest = false;
68
-
69
- const makeRequest = opts => {
82
+ const makeRequest = options_ => {
70
83
  madeRequest = true;
71
84
  let requestErrored = false;
72
85
  let requestErrorCallback;
73
-
74
86
  const requestErrorPromise = new Promise(resolve => {
75
87
  requestErrorCallback = () => {
76
88
  if (!requestErrored) {
@@ -79,11 +91,10 @@ class CacheableRequest {
79
91
  }
80
92
  };
81
93
  });
82
-
83
94
  const handler = response => {
84
- if (revalidate && !opts.forceRefresh) {
95
+ if (revalidate && !options_.forceRefresh) {
85
96
  response.status = response.statusCode;
86
- const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response);
97
+ const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(options_, response);
87
98
  if (!revalidatedPolicy.modified) {
88
99
  const headers = revalidatedPolicy.policy.responseHeaders();
89
100
  response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url);
@@ -93,39 +104,30 @@ class CacheableRequest {
93
104
  }
94
105
 
95
106
  if (!response.fromCache) {
96
- response.cachePolicy = new CachePolicy(opts, response, opts);
107
+ response.cachePolicy = new CachePolicy(options_, response, options_);
97
108
  response.fromCache = false;
98
109
  }
99
110
 
100
111
  let clonedResponse;
101
- if (opts.cache && response.cachePolicy.storable()) {
112
+ if (options_.cache && response.cachePolicy.storable()) {
102
113
  clonedResponse = cloneResponse(response);
103
-
104
114
  (async () => {
105
115
  try {
106
116
  const bodyPromise = getStream.buffer(response);
107
-
108
117
  await Promise.race([
109
118
  requestErrorPromise,
110
- new Promise(resolve => response.once('end', resolve))
119
+ new Promise(resolve => response.once('end', resolve)), // eslint-disable-line no-promise-executor-return
111
120
  ]);
112
-
113
- if (requestErrored) {
114
- return;
115
- }
116
-
117
121
  const body = await bodyPromise;
118
-
119
122
  const value = {
120
123
  cachePolicy: response.cachePolicy.toObject(),
121
124
  url: response.url,
122
125
  statusCode: response.fromCache ? revalidate.statusCode : response.statusCode,
123
- body
126
+ body,
124
127
  };
125
-
126
- let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined;
127
- if (opts.maxTtl) {
128
- ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl;
128
+ let ttl = options_.strictTtl ? response.cachePolicy.timeToLive() : undefined;
129
+ if (options_.maxTtl) {
130
+ ttl = ttl ? Math.min(ttl, options_.maxTtl) : options_.maxTtl;
129
131
  }
130
132
 
131
133
  await this.cache.set(key, value, ttl);
@@ -133,7 +135,7 @@ class CacheableRequest {
133
135
  ee.emit('error', new CacheableRequest.CacheError(error));
134
136
  }
135
137
  })();
136
- } else if (opts.cache && revalidate) {
138
+ } else if (options_.cache && revalidate) {
137
139
  (async () => {
138
140
  try {
139
141
  await this.cache.delete(key);
@@ -150,51 +152,48 @@ class CacheableRequest {
150
152
  };
151
153
 
152
154
  try {
153
- const req = request(opts, handler);
154
- req.once('error', requestErrorCallback);
155
- req.once('abort', requestErrorCallback);
156
- ee.emit('request', req);
155
+ const request_ = request(options_, handler);
156
+ request_.once('error', requestErrorCallback);
157
+ request_.once('abort', requestErrorCallback);
158
+ ee.emit('request', request_);
157
159
  } catch (error) {
158
160
  ee.emit('error', new CacheableRequest.RequestError(error));
159
161
  }
160
162
  };
161
163
 
162
164
  (async () => {
163
- const get = async opts => {
165
+ const get = async options_ => {
164
166
  await Promise.resolve();
165
-
166
- const cacheEntry = opts.cache ? await this.cache.get(key) : undefined;
167
+ const cacheEntry = options_.cache ? await this.cache.get(key) : undefined;
167
168
  if (typeof cacheEntry === 'undefined') {
168
- return makeRequest(opts);
169
+ return makeRequest(options_);
169
170
  }
170
171
 
171
172
  const policy = CachePolicy.fromObject(cacheEntry.cachePolicy);
172
- if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) {
173
+ if (policy.satisfiesWithoutRevalidation(options_) && !options_.forceRefresh) {
173
174
  const headers = policy.responseHeaders();
174
175
  const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url);
175
176
  response.cachePolicy = policy;
176
177
  response.fromCache = true;
177
-
178
178
  ee.emit('response', response);
179
179
  if (typeof cb === 'function') {
180
180
  cb(response);
181
181
  }
182
182
  } else {
183
183
  revalidate = cacheEntry;
184
- opts.headers = policy.revalidationHeaders(opts);
185
- makeRequest(opts);
184
+ options_.headers = policy.revalidationHeaders(options_);
185
+ makeRequest(options_);
186
186
  }
187
187
  };
188
188
 
189
189
  const errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error));
190
190
  this.cache.once('error', errorHandler);
191
191
  ee.on('response', () => this.cache.removeListener('error', errorHandler));
192
-
193
192
  try {
194
- await get(opts);
193
+ await get(options);
195
194
  } catch (error) {
196
- if (opts.automaticFailover && !madeRequest) {
197
- makeRequest(opts);
195
+ if (options.automaticFailover && !madeRequest) {
196
+ makeRequest(options);
198
197
  }
199
198
 
200
199
  ee.emit('error', new CacheableRequest.CacheError(error));
@@ -205,7 +204,6 @@ class CacheableRequest {
205
204
  };
206
205
  }
207
206
  }
208
-
209
207
  function urlObjectToRequestOptions(url) {
210
208
  const options = { ...url };
211
209
  options.path = `${url.pathname || '/'}${url.search || ''}`;
@@ -228,7 +226,7 @@ function normalizeUrlObject(url) {
228
226
  hostname: url.hostname || url.host || 'localhost',
229
227
  port: url.port,
230
228
  pathname: url.pathname,
231
- search: url.search
229
+ search: url.search,
232
230
  };
233
231
  }
234
232
 
@@ -239,7 +237,6 @@ CacheableRequest.RequestError = class extends Error {
239
237
  Object.assign(this, error);
240
238
  }
241
239
  };
242
-
243
240
  CacheableRequest.CacheError = class extends Error {
244
241
  constructor(error) {
245
242
  super(error.message);
@@ -248,4 +245,4 @@ CacheableRequest.CacheError = class extends Error {
248
245
  }
249
246
  };
250
247
 
251
- module.exports = CacheableRequest;
248
+ export default CacheableRequest;