cacheable-request 7.0.2 → 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 (4) hide show
  1. package/LICENSE +2 -1
  2. package/README.md +12 -10
  3. package/package.json +75 -26
  4. package/src/index.js +0 -251
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,6 @@ cacheableRequest('example.com', cb)
203
203
 
204
204
  ## License
205
205
 
206
- MIT © Luke Childs
206
+ MIT © Luke Childs 2017-2021
207
+
208
+ MIT © Jared Wray 2022
package/package.json CHANGED
@@ -1,20 +1,22 @@
1
1
  {
2
2
  "name": "cacheable-request",
3
- "version": "7.0.2",
3
+ "version": "8.3.0",
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)",
8
- "main": "src/index.js",
6
+ "repository": "jaredwray/cacheable-request",
7
+ "author": "Jared Wray <me@jaredwray.com> (http://jaredwray.com)",
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
9
10
  "engines": {
10
- "node": ">=8"
11
+ "node": ">=14.16"
11
12
  },
12
13
  "scripts": {
13
- "test": "xo && nyc ava",
14
- "coverage": "nyc report --reporter=text-lcov | coveralls"
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"
15
17
  },
16
18
  "files": [
17
- "src"
19
+ "dist"
18
20
  ],
19
21
  "keywords": [
20
22
  "HTTP",
@@ -29,28 +31,75 @@
29
31
  "compliant"
30
32
  ],
31
33
  "dependencies": {
32
- "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": "^6.0.1",
34
+ "get-stream": "^6.0.1",
35
+ "http-cache-semantics": "^4.1.0",
36
+ "keyv": "^4.3.2",
37
+ "mimic-response": "^3.1.0",
38
+ "normalize-url": "^6.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.5",
43
+ "@babel/preset-env": "^7.18.2",
44
+ "@keyv/sqlite": "^3.5.2",
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",
54
+ "create-test-server": "3.0.1",
55
+ "eslint-plugin-jest": "^26.5.3",
56
+ "delay": "^5.0.0",
57
+ "jest": "^28.1.1",
58
+ "pify": "^5.0.0",
59
+ "sqlite3": "^5.0.8",
60
+ "ts-jest": "^28.0.5",
61
+ "ts-node": "^10.8.1",
62
+ "typescript": "^4.7.4",
63
+ "xo": "^0.50.0"
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"
52
82
  },
53
83
  "xo": {
54
- "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
+ }
55
104
  }
56
105
  }
package/src/index.js DELETED
@@ -1,251 +0,0 @@
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
-
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
- this.cache = new Keyv({
20
- uri: typeof cacheAdapter === 'string' && cacheAdapter,
21
- store: typeof cacheAdapter !== 'string' && cacheAdapter,
22
- namespace: 'cacheable-request'
23
- });
24
-
25
- return this.createCacheableRequest(request);
26
- }
27
-
28
- createCacheableRequest(request) {
29
- return (opts, cb) => {
30
- 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 = {};
37
- } else {
38
- const [pathname, ...searchParts] = (opts.path || '').split('?');
39
- const search = searchParts.length > 0 ?
40
- `?${searchParts.join('?')}` :
41
- '';
42
- url = normalizeUrlObject({ ...opts, pathname, search });
43
- }
44
-
45
- opts = {
46
- headers: {},
47
- method: 'GET',
48
- cache: true,
49
- strictTtl: false,
50
- automaticFailover: false,
51
- ...opts,
52
- ...urlObjectToRequestOptions(url)
53
- };
54
- opts.headers = lowercaseKeys(opts.headers);
55
-
56
- const ee = new EventEmitter();
57
- const normalizedUrlString = normalizeUrl(
58
- urlLib.format(url),
59
- {
60
- stripWWW: false,
61
- removeTrailingSlash: false,
62
- stripAuthentication: false
63
- }
64
- );
65
- const key = `${opts.method}:${normalizedUrlString}`;
66
- let revalidate = false;
67
- let madeRequest = false;
68
-
69
- const makeRequest = opts => {
70
- madeRequest = true;
71
- let requestErrored = false;
72
- let requestErrorCallback;
73
-
74
- const requestErrorPromise = new Promise(resolve => {
75
- requestErrorCallback = () => {
76
- if (!requestErrored) {
77
- requestErrored = true;
78
- resolve();
79
- }
80
- };
81
- });
82
-
83
- const handler = response => {
84
- if (revalidate && !opts.forceRefresh) {
85
- response.status = response.statusCode;
86
- const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response);
87
- if (!revalidatedPolicy.modified) {
88
- const headers = revalidatedPolicy.policy.responseHeaders();
89
- response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url);
90
- response.cachePolicy = revalidatedPolicy.policy;
91
- response.fromCache = true;
92
- }
93
- }
94
-
95
- if (!response.fromCache) {
96
- response.cachePolicy = new CachePolicy(opts, response, opts);
97
- response.fromCache = false;
98
- }
99
-
100
- let clonedResponse;
101
- if (opts.cache && response.cachePolicy.storable()) {
102
- clonedResponse = cloneResponse(response);
103
-
104
- (async () => {
105
- try {
106
- const bodyPromise = getStream.buffer(response);
107
-
108
- await Promise.race([
109
- requestErrorPromise,
110
- new Promise(resolve => response.once('end', resolve))
111
- ]);
112
-
113
- if (requestErrored) {
114
- return;
115
- }
116
-
117
- const body = await bodyPromise;
118
-
119
- const value = {
120
- cachePolicy: response.cachePolicy.toObject(),
121
- url: response.url,
122
- statusCode: response.fromCache ? revalidate.statusCode : response.statusCode,
123
- body
124
- };
125
-
126
- let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined;
127
- if (opts.maxTtl) {
128
- ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl;
129
- }
130
-
131
- await this.cache.set(key, value, ttl);
132
- } catch (error) {
133
- ee.emit('error', new CacheableRequest.CacheError(error));
134
- }
135
- })();
136
- } else if (opts.cache && revalidate) {
137
- (async () => {
138
- try {
139
- await this.cache.delete(key);
140
- } catch (error) {
141
- ee.emit('error', new CacheableRequest.CacheError(error));
142
- }
143
- })();
144
- }
145
-
146
- ee.emit('response', clonedResponse || response);
147
- if (typeof cb === 'function') {
148
- cb(clonedResponse || response);
149
- }
150
- };
151
-
152
- try {
153
- const req = request(opts, handler);
154
- req.once('error', requestErrorCallback);
155
- req.once('abort', requestErrorCallback);
156
- ee.emit('request', req);
157
- } catch (error) {
158
- ee.emit('error', new CacheableRequest.RequestError(error));
159
- }
160
- };
161
-
162
- (async () => {
163
- const get = async opts => {
164
- await Promise.resolve();
165
-
166
- const cacheEntry = opts.cache ? await this.cache.get(key) : undefined;
167
- if (typeof cacheEntry === 'undefined') {
168
- return makeRequest(opts);
169
- }
170
-
171
- const policy = CachePolicy.fromObject(cacheEntry.cachePolicy);
172
- if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) {
173
- const headers = policy.responseHeaders();
174
- const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url);
175
- response.cachePolicy = policy;
176
- response.fromCache = true;
177
-
178
- ee.emit('response', response);
179
- if (typeof cb === 'function') {
180
- cb(response);
181
- }
182
- } else {
183
- revalidate = cacheEntry;
184
- opts.headers = policy.revalidationHeaders(opts);
185
- makeRequest(opts);
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
-
193
- try {
194
- await get(opts);
195
- } catch (error) {
196
- if (opts.automaticFailover && !madeRequest) {
197
- makeRequest(opts);
198
- }
199
-
200
- ee.emit('error', new CacheableRequest.CacheError(error));
201
- }
202
- })();
203
-
204
- return ee;
205
- };
206
- }
207
- }
208
-
209
- function urlObjectToRequestOptions(url) {
210
- const options = { ...url };
211
- options.path = `${url.pathname || '/'}${url.search || ''}`;
212
- delete options.pathname;
213
- delete options.search;
214
- return options;
215
- }
216
-
217
- function normalizeUrlObject(url) {
218
- // If url was parsed by url.parse or new URL:
219
- // - hostname will be set
220
- // - host will be hostname[:port]
221
- // - port will be set if it was explicit in the parsed string
222
- // Otherwise, url was from request options:
223
- // - hostname or host may be set
224
- // - host shall not have port encoded
225
- return {
226
- protocol: url.protocol,
227
- auth: url.auth,
228
- hostname: url.hostname || url.host || 'localhost',
229
- port: url.port,
230
- pathname: url.pathname,
231
- search: url.search
232
- };
233
- }
234
-
235
- CacheableRequest.RequestError = class extends Error {
236
- constructor(error) {
237
- super(error.message);
238
- this.name = 'RequestError';
239
- Object.assign(this, error);
240
- }
241
- };
242
-
243
- CacheableRequest.CacheError = class extends Error {
244
- constructor(error) {
245
- super(error.message);
246
- this.name = 'CacheError';
247
- Object.assign(this, error);
248
- }
249
- };
250
-
251
- module.exports = CacheableRequest;