cacheable-request 8.0.1 → 8.3.0

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 (3) hide show
  1. package/README.md +1 -0
  2. package/package.json +66 -18
  3. package/src/index.js +0 -248
package/README.md CHANGED
@@ -204,4 +204,5 @@ cacheableRequest('example.com', cb)
204
204
  ## License
205
205
 
206
206
  MIT © Luke Childs 2017-2021
207
+
207
208
  MIT © Jared Wray 2022
package/package.json CHANGED
@@ -1,22 +1,22 @@
1
1
  {
2
2
  "name": "cacheable-request",
3
- "version": "8.0.1",
3
+ "version": "8.3.0",
4
4
  "description": "Wrap native HTTP requests with RFC compliant cache support",
5
5
  "license": "MIT",
6
6
  "repository": "jaredwray/cacheable-request",
7
7
  "author": "Jared Wray <me@jaredwray.com> (http://jaredwray.com)",
8
- "type": "module",
9
- "main": "src/index.js",
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
10
  "engines": {
11
- "node": ">=14"
11
+ "node": ">=14.16"
12
12
  },
13
13
  "scripts": {
14
- "test": "xo && nyc ava",
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"
14
+ "test": "xo && jest --coverage",
15
+ "build": "tsc --project tsconfig.build.json",
16
+ "clean": "rm -rf node_modules && rm -rf ./coverage && rm -rf ./package-lock.json && rm -rf ./test/testdb.sqlite && rm -rf ./dist"
17
17
  },
18
18
  "files": [
19
- "src"
19
+ "dist"
20
20
  ],
21
21
  "keywords": [
22
22
  "HTTP",
@@ -31,27 +31,75 @@
31
31
  "compliant"
32
32
  ],
33
33
  "dependencies": {
34
- "clone-response": "^1.0.2",
35
34
  "get-stream": "^6.0.1",
36
35
  "http-cache-semantics": "^4.1.0",
37
- "keyv": "^4.3.0",
38
- "normalize-url": "^7.0.3",
36
+ "keyv": "^4.3.2",
37
+ "mimic-response": "^3.1.0",
38
+ "normalize-url": "^6.0.3",
39
39
  "responselike": "^2.0.0"
40
40
  },
41
41
  "devDependencies": {
42
- "@babel/core": "^7.18.2",
43
- "@babel/register": "^7.17.7",
42
+ "@babel/core": "^7.18.5",
43
+ "@babel/preset-env": "^7.18.2",
44
44
  "@keyv/sqlite": "^3.5.2",
45
- "ava": "^4.3.0",
45
+ "@types/create-test-server": "^3.0.1",
46
+ "@types/delay": "^3.1.0",
47
+ "@types/get-stream": "^3.0.2",
48
+ "@types/http-cache-semantics": "^4.0.1",
49
+ "@types/jest": "^28.1.3",
50
+ "@types/node": "^18.0.0",
51
+ "@types/pify": "^5.0.1",
52
+ "@types/responselike": "^1.0.0",
53
+ "@types/sqlite3": "^3.1.8",
46
54
  "create-test-server": "3.0.1",
55
+ "eslint-plugin-jest": "^26.5.3",
47
56
  "delay": "^5.0.0",
48
- "eslint-config-xo-lukechilds": "^1.0.1",
49
- "nyc": "^15.1.0",
50
- "pify": "^6.0.0",
57
+ "jest": "^28.1.1",
58
+ "pify": "^5.0.0",
51
59
  "sqlite3": "^5.0.8",
60
+ "ts-jest": "^28.0.5",
61
+ "ts-node": "^10.8.1",
62
+ "typescript": "^4.7.4",
52
63
  "xo": "^0.50.0"
53
64
  },
65
+ "jest": {
66
+ "globals": {
67
+ "ts-jest": {
68
+ "tsconfig": "./tsconfig.json"
69
+ }
70
+ },
71
+ "moduleFileExtensions": [
72
+ "ts",
73
+ "js"
74
+ ],
75
+ "transform": {
76
+ "^.+\\.(ts|tsx)$": "ts-jest"
77
+ },
78
+ "testMatch": [
79
+ "**/test/*.test.(ts)"
80
+ ],
81
+ "testEnvironment": "node"
82
+ },
54
83
  "xo": {
55
- "extends": "xo-lukechilds"
84
+ "plugins": [
85
+ "jest"
86
+ ],
87
+ "extends": [
88
+ "plugin:jest/recommended"
89
+ ],
90
+ "rules": {
91
+ "@typescript-eslint/object-curly-spacing": 0,
92
+ "@typescript-eslint/naming-convention": 0,
93
+ "@typescript-eslint/no-unsafe-assignment": 0,
94
+ "@typescript-eslint/no-unsafe-call": 0,
95
+ "@typescript-eslint/ban-types": 0,
96
+ "@typescript-eslint/restrict-template-expressions": 0,
97
+ "@typescript-eslint/no-unsafe-return": 0,
98
+ "new-cap": 0,
99
+ "@typescript-eslint/no-empty-function": 0,
100
+ "@typescript-eslint/restrict-plus-operands": 0,
101
+ "@typescript-eslint/no-floating-promises": 0,
102
+ "@typescript-eslint/await-thenable": 0
103
+ }
56
104
  }
57
105
  }
package/src/index.js DELETED
@@ -1,248 +0,0 @@
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
- class CacheableRequest {
14
- constructor(request, cacheAdapter) {
15
- if (typeof request !== 'function') {
16
- throw new TypeError('Parameter `request` must be a function');
17
- }
18
-
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
- }
28
-
29
- return this.createCacheableRequest(request); // eslint-disable-line no-constructor-return
30
- }
31
-
32
- createCacheableRequest(request) {
33
- return (options, cb) => {
34
- let url;
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 = {};
41
- } else {
42
- const [pathname, ...searchParts] = (options.path || '').split('?');
43
- const search = searchParts.length > 0
44
- ? `?${searchParts.join('?')}`
45
- : '';
46
- url = normalizeUrlObject({ ...options, pathname, search });
47
- }
48
-
49
- options = {
50
- headers: {},
51
- method: 'GET',
52
- cache: true,
53
- strictTtl: false,
54
- automaticFailover: false,
55
- ...options,
56
- ...urlObjectToRequestOptions(url),
57
- };
58
- options.headers = Object.fromEntries(Object.entries(options.headers).map(([key, value]) => [key.toLowerCase(), value]));
59
- const ee = new EventEmitter();
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')}`;
77
- }
78
- }
79
-
80
- let revalidate = false;
81
- let madeRequest = false;
82
- const makeRequest = options_ => {
83
- madeRequest = true;
84
- let requestErrored = false;
85
- let requestErrorCallback;
86
- const requestErrorPromise = new Promise(resolve => {
87
- requestErrorCallback = () => {
88
- if (!requestErrored) {
89
- requestErrored = true;
90
- resolve();
91
- }
92
- };
93
- });
94
- const handler = response => {
95
- if (revalidate && !options_.forceRefresh) {
96
- response.status = response.statusCode;
97
- const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(options_, response);
98
- if (!revalidatedPolicy.modified) {
99
- const headers = revalidatedPolicy.policy.responseHeaders();
100
- response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url);
101
- response.cachePolicy = revalidatedPolicy.policy;
102
- response.fromCache = true;
103
- }
104
- }
105
-
106
- if (!response.fromCache) {
107
- response.cachePolicy = new CachePolicy(options_, response, options_);
108
- response.fromCache = false;
109
- }
110
-
111
- let clonedResponse;
112
- if (options_.cache && response.cachePolicy.storable()) {
113
- clonedResponse = cloneResponse(response);
114
- (async () => {
115
- try {
116
- const bodyPromise = getStream.buffer(response);
117
- await Promise.race([
118
- requestErrorPromise,
119
- new Promise(resolve => response.once('end', resolve)), // eslint-disable-line no-promise-executor-return
120
- ]);
121
- const body = await bodyPromise;
122
- const value = {
123
- cachePolicy: response.cachePolicy.toObject(),
124
- url: response.url,
125
- statusCode: response.fromCache ? revalidate.statusCode : response.statusCode,
126
- body,
127
- };
128
- let ttl = options_.strictTtl ? response.cachePolicy.timeToLive() : undefined;
129
- if (options_.maxTtl) {
130
- ttl = ttl ? Math.min(ttl, options_.maxTtl) : options_.maxTtl;
131
- }
132
-
133
- await this.cache.set(key, value, ttl);
134
- } catch (error) {
135
- ee.emit('error', new CacheableRequest.CacheError(error));
136
- }
137
- })();
138
- } else if (options_.cache && revalidate) {
139
- (async () => {
140
- try {
141
- await this.cache.delete(key);
142
- } catch (error) {
143
- ee.emit('error', new CacheableRequest.CacheError(error));
144
- }
145
- })();
146
- }
147
-
148
- ee.emit('response', clonedResponse || response);
149
- if (typeof cb === 'function') {
150
- cb(clonedResponse || response);
151
- }
152
- };
153
-
154
- try {
155
- const request_ = request(options_, handler);
156
- request_.once('error', requestErrorCallback);
157
- request_.once('abort', requestErrorCallback);
158
- ee.emit('request', request_);
159
- } catch (error) {
160
- ee.emit('error', new CacheableRequest.RequestError(error));
161
- }
162
- };
163
-
164
- (async () => {
165
- const get = async options_ => {
166
- await Promise.resolve();
167
- const cacheEntry = options_.cache ? await this.cache.get(key) : undefined;
168
- if (typeof cacheEntry === 'undefined') {
169
- return makeRequest(options_);
170
- }
171
-
172
- const policy = CachePolicy.fromObject(cacheEntry.cachePolicy);
173
- if (policy.satisfiesWithoutRevalidation(options_) && !options_.forceRefresh) {
174
- const headers = policy.responseHeaders();
175
- const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url);
176
- response.cachePolicy = policy;
177
- response.fromCache = true;
178
- ee.emit('response', response);
179
- if (typeof cb === 'function') {
180
- cb(response);
181
- }
182
- } else {
183
- revalidate = cacheEntry;
184
- options_.headers = policy.revalidationHeaders(options_);
185
- makeRequest(options_);
186
- }
187
- };
188
-
189
- const errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error));
190
- this.cache.once('error', errorHandler);
191
- ee.on('response', () => this.cache.removeListener('error', errorHandler));
192
- try {
193
- await get(options);
194
- } catch (error) {
195
- if (options.automaticFailover && !madeRequest) {
196
- makeRequest(options);
197
- }
198
-
199
- ee.emit('error', new CacheableRequest.CacheError(error));
200
- }
201
- })();
202
-
203
- return ee;
204
- };
205
- }
206
- }
207
- function urlObjectToRequestOptions(url) {
208
- const options = { ...url };
209
- options.path = `${url.pathname || '/'}${url.search || ''}`;
210
- delete options.pathname;
211
- delete options.search;
212
- return options;
213
- }
214
-
215
- function normalizeUrlObject(url) {
216
- // If url was parsed by url.parse or new URL:
217
- // - hostname will be set
218
- // - host will be hostname[:port]
219
- // - port will be set if it was explicit in the parsed string
220
- // Otherwise, url was from request options:
221
- // - hostname or host may be set
222
- // - host shall not have port encoded
223
- return {
224
- protocol: url.protocol,
225
- auth: url.auth,
226
- hostname: url.hostname || url.host || 'localhost',
227
- port: url.port,
228
- pathname: url.pathname,
229
- search: url.search,
230
- };
231
- }
232
-
233
- CacheableRequest.RequestError = class extends Error {
234
- constructor(error) {
235
- super(error.message);
236
- this.name = 'RequestError';
237
- Object.assign(this, error);
238
- }
239
- };
240
- CacheableRequest.CacheError = class extends Error {
241
- constructor(error) {
242
- super(error.message);
243
- this.name = 'CacheError';
244
- Object.assign(this, error);
245
- }
246
- };
247
-
248
- export default CacheableRequest;