@ohos-ports/express-redis-cache 0.0.0-stage → 1.1.3-beta.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.
package/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ language: node_js
2
+ node_js:
3
+ - "8.11.3"
4
+ - "10.5.0"
5
+ services:
6
+ - redis
package/CHANGELOG.md ADDED
@@ -0,0 +1,93 @@
1
+ CHANGE LOG
2
+ ==========
3
+
4
+ # Changes between 0.0.8 and 0.1.x
5
+
6
+ ## Disclaimer
7
+
8
+ Even though we updated the major version in the semantic version (from 0.0.x to 0.1.x), this version has been designed so there would be **no breaking changes** and that clients may **safely upgrade** -- keeping in mind we ship `as-is`.
9
+
10
+ So why having incremented the major version then? It reflects that architectural changes have been made (view below) to redesign, normalize and standardize the codebase (better documentation, better syntax, better tests, etc.) -- yet, once again, these changes should not have an impact for clients upgrading (no code change required on their side).
11
+
12
+ ## New features
13
+
14
+ ### Conditional caching
15
+
16
+ We introduced the `(Boolean) res.express_redis_cache_skip` property which, if set to true, will not cache the route nor use the cache -- it will skip `cache.route()` altogether (see README for more info, look for Conditional caching).
17
+
18
+ ### Deprecated event
19
+
20
+ The code now emits a *deprecated* event when stumbling upon a deprecated part of the code. View below for more info.
21
+
22
+ ## Fixes
23
+
24
+ No fixes have been made.
25
+
26
+ ## Changed
27
+
28
+ ### Test
29
+
30
+ We now use Mocha and should.js for testing instead of home-made testing framework
31
+
32
+ ### Event Emitter
33
+
34
+ Module (`index.js`) now extends EventEmitter to emit events instead of custome event emitter before
35
+
36
+ ### Use strict
37
+
38
+ We now use strict JavaScript
39
+
40
+ ### Contributors
41
+
42
+ Added all the kind people who submit PRs to the list of contributors
43
+
44
+ ### Module is now an object instead of a function
45
+
46
+ ### Naming convention
47
+
48
+ Code base now strictly follows the following naming convention:
49
+
50
+ - Class names are in upper camel case (ie, `function MyClass () {}`)
51
+ - Function and method names are in lower camel case (ie, `function myFunction () {}`)
52
+ - Variable names are in lower snake case (ie, `var my_var;`)
53
+ - Constant names are in upper case (even though we don't use the `const` keyword to declare them because it is not allowed in strict JavaScript) (ie, `var CONSTANT = 1`)
54
+
55
+ The variables from the previous code who are not following the naming convention are marked as deprecated (you can still use them) and their equivalent with the correct naming have been introduced (we recomend you to use them instead). See the section **## Deprecated** below.
56
+
57
+ ## Deprecated
58
+
59
+ Still supported, but will issue a deprecation notice with a substitute. You can get notified like this:
60
+
61
+ ```js
62
+ cache.on("deprecated", function (deprecated, substitute) {
63
+ console.log('Deprecated: ' + deprecated +'. Use ' + substitute + ' instead');
64
+ });
65
+ ```
66
+
67
+ ### expressRedisCacheName
68
+
69
+ Now use `express_redis_cache_name`
70
+
71
+ ```js
72
+ // Replace
73
+ res.expressRedisCacheName = "...";
74
+
75
+ // By
76
+ res.express_redis_cache_name = "...";
77
+ ```
78
+
79
+ ### expressRedisCache
80
+
81
+ Now use `use_express_redis_cache`
82
+
83
+ ```js
84
+ // Replace
85
+ if ( res.expressRedisCache ) {}
86
+
87
+ // By
88
+ if ( res.use_express_redis_cache ) {}
89
+ ```
90
+
91
+ ## Removed
92
+
93
+ - the `ls` method have been removed both from API and CLI. Use `get` instead.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) [year] [fullname]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,495 @@
1
- # Temporary Holding Version
1
+ express-redis-cache
2
+ ===
2
3
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
4
+ [![Build Status](https://travis-ci.org/rv-kip/express-redis-cache.svg?branch=master)](https://travis-ci.org/rv-kip/express-redis-cache)
5
+ [![dependencies Status](https://david-dm.org/rv-kip/express-redis-cache/status.svg)](https://david-dm.org/rv-kip/express-redis-cache)
6
+
7
+ Easily cache pages of your app using Express and Redis. *Could be used without Express too.*
8
+
9
+ # Install
10
+
11
+ npm install express-redis-cache
12
+
13
+ `express-redis-cache` ships with a CLI utility you can invoke from the console. In order to use it, install `express-redis-cache` globally (might require super user privileges):
14
+
15
+ npm install -g express-redis-cache
16
+
17
+ # Upgrade
18
+
19
+ Read [this](../master/CHANGELOG.md) if you are upgrading from 0.0.8 to 0.1.x,
20
+
21
+ # Usage
22
+
23
+ Just use it as a middleware in the stack of the route you want to cache.
24
+
25
+ ```js
26
+ var app = express();
27
+ var cache = require('express-redis-cache')();
28
+
29
+ // replace
30
+ app.get('/',
31
+ function (req, res) { ... });
32
+
33
+ // by
34
+ app.get('/',
35
+ cache.route(),
36
+ function (req, res) { ... });
37
+ ```
38
+
39
+ This will check if there is a cache entry for this route. If not. it will cache it and serve the cache next time route is called.
40
+
41
+ # Redis connection info
42
+
43
+ By default, `redis-express-cache` connects to Redis using localhost as host and nothing as port (using Redis default port 6379). To use different port or host, declare them when you require express-redis-cache. If your Redis server requires password, use the `auth_pass` option.
44
+
45
+ ```js
46
+ var cache = require('express-redis-cache')({
47
+ host: String, port: Number, auth_pass: REDIS_PASSWORD
48
+ });
49
+ ```
50
+
51
+ You can pass a Redis client as well:
52
+
53
+ ```js
54
+ require('express-redis-cache')({ client: require('redis').createClient() })
55
+ ```
56
+
57
+ You can have several clients if you want to serve from more than one Redis server:
58
+
59
+ ```js
60
+ var cache = require('express-redis-cache');
61
+ var client1 = cache({ host: "...", port: "..." });
62
+ var client2 = cache({ host: "...", port: "..." });
63
+ ...
64
+ ```
65
+ ## Redis Unavailability
66
+ Should the redis become unavailable, the `express-redis-cache` object will emit errors but will not crash the app. Express.js requests during this time will be bypass cache and will return fresh data.
67
+
68
+ Once the redis recovers, the caching will begin working again. See example code in the `/example` folder.
69
+
70
+ # Name of the cache entry
71
+
72
+ By default, the cache entry name will be `default prefix`:`name` where name's value defaults to [req.originalUrl](http://expressjs.com/4x/api.html#req.originalUrl).
73
+
74
+ ```js
75
+ app.get('/',
76
+ cache.route(), // cache entry name is `cache.prefix + "/"`
77
+ function (req, res) { ... });
78
+ ```
79
+
80
+ You can specify a custom name like this:
81
+
82
+ ```js
83
+ app.get('/',
84
+ cache.route('home'), // cache entry name is now `cache.prefix + "home"`
85
+ function (req, res) { ... });
86
+ ```
87
+
88
+ You can also use the object syntax:
89
+
90
+ ```js
91
+ app.get('/',
92
+ cache.route({ name: 'home' }), // cache entry name is `cache.prefix + "home"`
93
+ function (req, res) { ... });
94
+ ```
95
+
96
+ Also, you can use `res.express_redis_cache_name` to specify the name of the entry such as:
97
+
98
+ ```js
99
+ app.get('/user/:userid',
100
+
101
+ // middleware to define cache name
102
+
103
+ function (req, res, next) {
104
+ // set cache name
105
+ res.express_redis_cache_name = 'user-' + req.params.userid;
106
+ next();
107
+ },
108
+
109
+ // cache middleware
110
+
111
+ cache.route(),
112
+
113
+ // content middleware
114
+
115
+ function (req, res) {
116
+ res.render('user');
117
+ }
118
+
119
+ );
120
+ ```
121
+
122
+ # Conditional caching
123
+
124
+ You can also use a previous middleware to set whether or not to use the cache by using `res.use_express_redis_cache`:
125
+
126
+ ```js
127
+
128
+ app.get('/user',
129
+
130
+ // middleware to decide if using cache
131
+
132
+ function (req, res, next) {
133
+ // Use only cache if user not signed in
134
+ res.use_express_redis_cache = ! req.signedCookies.user;
135
+
136
+ next();
137
+ }.
138
+
139
+ cache.route(), // this will be skipped if user is signed in
140
+
141
+ function (req, res) {
142
+ res.render('user');
143
+ }
144
+ );
145
+ ```
146
+
147
+ # Prefix
148
+
149
+ All entry names are prepended by a prefix. Prefix is set when calling the Constructor.
150
+
151
+ ```js
152
+ // Set default prefix to "test". All entry names will begin by "test:"
153
+ var cache = require('express-redis-cache')({ prefix: 'test' });
154
+ ```
155
+
156
+ To know the prefix:
157
+
158
+ ```js
159
+ console.log('prefix', cache.prefix);
160
+ ```
161
+
162
+ You can pass a custom prefix when calling `route()`:
163
+
164
+ ```js
165
+ app.get('/index.html',
166
+ cache.route('index', { prefix: 'test' }), // force prefix to be "test", entry name will be "test:index"
167
+ function (req, res) { ... });
168
+ ```
169
+
170
+ You can also choose not to use prefixes:
171
+
172
+ ```js
173
+ app.get('/index.html',
174
+ cache.route({ prefix: false }), // no prefixing, entry name will be "/index.html"
175
+ function (req, res) { ... });
176
+ ```
177
+
178
+ # Expiration
179
+
180
+ Unless specified otherwise when calling the Constructor, cache entries don't expire. You can specify a default lifetime when calling the constructor:
181
+
182
+ ```js
183
+ // Set default lifetime to 60 seconds for all entries
184
+ var cache = require('express-redis-cache')({ expire: 60 });
185
+ ```
186
+
187
+ You can overwrite the default lifetime when calling `route()`:
188
+
189
+ ```js
190
+ app.get('/index.html',
191
+ cache.route({ expire: 5000 }), // cache entry will live 5000 seconds
192
+ function (req, res) { ... });
193
+
194
+ // You can also use the number sugar syntax
195
+ cache.route(5000);
196
+ // Or
197
+ cache.route('index', 5000);
198
+ // Or
199
+ cache.route({ prefix: 'test' }, 5000);
200
+ ```
201
+
202
+ You can also provide a hash of status code / expiration values if you for example want to retry much sooner in failure cases (403/404/500/etc). Status ranges can be specified via `4xx`/`5xx`. You must provide a default value (`xxx`). The most specific rule will be used. For example, if the status code is 200, and there are expirations set for 200, 2xx, and xxx, the expiration for 200 will be used.
203
+
204
+ ```js
205
+ app.get('/index.html',
206
+ cache.route({
207
+ expire: {
208
+ 200: 5000,
209
+ 4xx: 10,
210
+ 403: 5000,
211
+ 5xx: 10,
212
+ xxx: 1
213
+ }
214
+ }),
215
+ function (req, res) { ... });
216
+ ```
217
+
218
+ You can also specify
219
+
220
+ # Content Type
221
+
222
+ You can use `express-redis-cache` to cache HTML pages, CSS stylesheets, JSON objects, anything really. Content-types are saved along the cache body and are retrieved using `res._headers['content-type']`. If you want to overwrite that, you can pass a custom type.
223
+
224
+ ```js
225
+ app.get('/index.html',
226
+ cache.route({ type: 'text/plain' }), // force entry type to be "text/plain"
227
+ function (req, res) { ... });
228
+ ```
229
+
230
+ # Events
231
+
232
+ The module emits the following events:
233
+
234
+ ## error
235
+
236
+ You can catch errors by adding a listener:
237
+
238
+ ```js
239
+ cache.on('error', function (error) {
240
+ throw new Error('Cache error!');
241
+ });
242
+ ```
243
+
244
+ ## message
245
+
246
+ `express-redis-cache` logs some information at runtime. You can access it like this:
247
+
248
+ ```js
249
+ cache.on('message', function (message) {
250
+ // ...
251
+ });
252
+ ```
253
+
254
+ ## connected
255
+
256
+ Emitted when the client is connected (or re-connected) to Redis server
257
+
258
+ ```js
259
+ cache.on('connected', function () {
260
+ // ....
261
+ });
262
+ ```
263
+
264
+ ## disconnected
265
+
266
+ Emitted when the client is disconnected from Redis server. When (and if) it reconnects, it will emit a 'connected' event again
267
+
268
+ ```js
269
+ cache.on('disconnected', function () {
270
+ // ....
271
+ });
272
+ ```
273
+
274
+ **Note** You can get the connexion status at any time by getting the property `cache.connected` which returns a boolean (true = connected, false = disconnected).
275
+
276
+ ## deprecated
277
+
278
+ Warning emitted when stumbled upon a deprecated part of the code
279
+
280
+ ```js
281
+ cache.on('deprecated', function (deprecated) {
282
+ console.log('deprecated warning', {
283
+ type: deprecated.type,
284
+ name: deprecated.name,
285
+ substitute: deprecated.substitute,
286
+ file: deprecated.file,
287
+ line: deprecated.line
288
+ });
289
+ });
290
+ ```
291
+
292
+ # The Entry Model
293
+
294
+ This is the object synopsis we use to represent a cache entry:
295
+
296
+ ```js
297
+ var entry = {
298
+ body: String // the content of the cache
299
+ touched: Number // last time cache was set (created or updated) as a Unix timestamp
300
+ expire: Number // the seconds cache entry lives (-1 if does not expire)
301
+ type: String // the content-type
302
+ };
303
+ ```
304
+
305
+ # The module
306
+
307
+ The module exposes a function which instantiates a new instance of a class called [ExpressRedisCache](../master/index.js).
308
+
309
+ ```js
310
+ // This
311
+ var cache = require('express-redis-cache')({ /* ... */ });
312
+ // is the same than
313
+ var cache = new (require('express-redis-cache/lib/ExpressRedisCache'))({ /* ... */ });
314
+ ```
315
+
316
+ # The constructor
317
+
318
+ As stated above, call the function exposed by the module to create a new instance of `ExpressRedisCache`,
319
+
320
+ ```js
321
+ var cache = require('express-redis-cache')(/** Object | Undefined */ options);
322
+ ```
323
+
324
+ Where `options` is an object that has the following properties:
325
+
326
+ | Option | Type | Default | Description |
327
+ | ------------- |----------|-------|----------|--------|
328
+ | **host** | `String` | `undefined` | Redis server host
329
+ | **port** | `Number` | `undefined` | Redis server port
330
+ | **prefix** | `String` | `require('express-redis-cache/package.json').config.prefix` | Default prefix (This will be prepended to all entry names) |
331
+ | **expire** | `Number` | `undefined` | Default life time of entries in seconds |
332
+ | **client** | `RedisClient` | `require('redis').createClient({ host: cache.host, port: cache.port })` | A Redis client |
333
+
334
+ # API
335
+
336
+ The `route` method is designed to integrate easily with Express. You can also define your own caching logics using the other methos of the API shown below.
337
+
338
+ ## `get` Get cache entries
339
+
340
+ ```js
341
+ cache.get(/** Mixed (optional) */ query, /** Function( Error, [Entry] ) */ callback );
342
+ ```
343
+
344
+ To get all cache entries:
345
+
346
+ ```js
347
+ cache.get(function (error, entries) {
348
+ if ( error ) throw error;
349
+
350
+ entries.forEach(console.log.bind(console));
351
+ });
352
+ ```
353
+
354
+ To get a specific entry:
355
+
356
+ ```js
357
+ cache.get('home', function (error, entries) {});
358
+ ```
359
+
360
+ To get a specific entry for a given prefix:
361
+
362
+ ```js
363
+ cache.get({ name: 'home', prefix: 'test' }, function (error, entries) {});
364
+ ```
365
+
366
+ You can use wildcard:
367
+
368
+ ```js
369
+ cache.get('user*', function (error, entries) {});
370
+ ```
371
+
372
+ ## `add` Add a new cache entry
373
+
374
+ ```js
375
+ cache.add(/** String */ name, /** String */ body, /** Object (optional) **/ options, /** Function( Error, Entry ) */ callback )
376
+ ```
377
+
378
+ Where options is an object that can have the following properties:
379
+
380
+ - **expire** `Number` (lifetime of entry in seconds)
381
+ - **type** `String` (the content-type)
382
+
383
+ Example:
384
+
385
+ ```js
386
+ cache.add('user:info', JSON.stringify({ id: 1, email: 'john@doe.com' }), { expire: 60 * 60 * 24, type: 'json' },
387
+ function (error, added) {});
388
+ ```
389
+
390
+ ## `del` Delete a cache entry
391
+
392
+ ```js
393
+ cache.del(/** String */ name, /** Function ( Error, Number deletions ) */ callback);
394
+ ```
395
+
396
+ You can use wildcard (*) in name.
397
+
398
+ ## `size` Get cache size for all entries
399
+
400
+ ```js
401
+ cache.size(/** Function ( Error, Number bytes ) */);
402
+ ```
403
+
404
+ # Command line
405
+
406
+ We ship with a CLI. You can invoke it like this: `express-redis-cache`
407
+
408
+ ## View cache entries
409
+
410
+ ```bash
411
+ express-redis-cache ls
412
+ ```
413
+
414
+ ## Add cache entry
415
+
416
+ ```bash
417
+ express-redis-cache add $name $body $expire --type $type
418
+ ```
419
+
420
+ ### Examples
421
+
422
+ ```bash
423
+ # Cache simple text
424
+ express-redis-cache add "test" "This is a test";
425
+
426
+ # Cache a file
427
+ express-redis-cache add "home" "$(cat index.html)";
428
+
429
+ # Cache a JSON object
430
+ express-redis-cache add "user1:location" '{ "lat": 4.7453, "lng": -31.332 }' --type json;
431
+
432
+ # Cache a text that will expire in one hour
433
+ express-redis-cache add "offer" "everything 25% off for the next hour" $(( 60 * 60 ));
434
+ ```
435
+
436
+ ## Get single cache entry
437
+
438
+ ```bash
439
+ express-redis-cache get $name
440
+ # Example: express-redis-cache get user1:*
441
+ # Output:
442
+ ```
443
+
444
+ ## Delete cache entry
445
+
446
+ ```bash
447
+ express-redis-cache del $name
448
+ # Example: express-redis-cache del user1:*
449
+ # Output:
450
+ ```
451
+
452
+ ## Get total cache size
453
+
454
+ ```bash
455
+ express-redis-cache size
456
+ # Output:
457
+ ```
458
+ # Example Code
459
+ Run the example to see how the caching behaves. You can kill the `redis-server` and the application will respond with non-cached information.
460
+ ```
461
+ npm install
462
+ cd example
463
+ node example.js
464
+ ```
465
+
466
+ # Test
467
+
468
+ We use Mocha and Should for the tests. You can invoke tests like this:
469
+
470
+ npm test
471
+
472
+ ## Test environments
473
+
474
+ You can specify the following environments before running your tests:
475
+
476
+ ```bash
477
+ export EX_RE_CA_HOST="";
478
+ export EX_RE_CA_PORT="";
479
+ export EX_RE_CA_PREFIX="";
480
+ ```
481
+
482
+ # Contributors
483
+
484
+ - [faceair](https://github.com/faceair)
485
+ - [barwin](https://github.com/barwin)
486
+ - [rv-kip](https://github.com/rv-kip)
487
+ - [amaurigabriel](https://github.com/amaurigabriel)
488
+ - [benmcmeen](https://github.com/benmcmeen)
489
+ - [pwmckenna](https://github.com/pwmckenna)
490
+ - [mattberther](https://github.com/mattberther)
491
+ - [ramanpreetnara](https://github.com/ramanpreetnara)
492
+
493
+ ---
494
+
495
+ Enjoy!