• Stars
    star
    129
  • Rank 279,262 (Top 6 %)
  • Language
    JavaScript
  • Created over 11 years ago
  • Updated almost 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Lightweight Redis adapter for Node.js/Sails apps, focused on providing easy direct access to the configured, connected, ready-to-use Redis client instance. (Useful for caching.)

sails-redisimage_squidhome@2x.png

Lightweight Redis Adapter for Node.js / Sails Apps

A lightweight Sails/Waterline adapter for Redis. May be used in a Sails app, or any Node.js module using Waterline as its ORM.

Heads up

This adapter does not support the Semantic or Queryable interfaces. Instead, it simply provides robust, managed access to the underlying Redis client. That means you can't use it to call methods like .find(). Instead, use it as a simple way to easily configure, obtain a connection, and communicate with Redis (e.g. for caching) within the lifecycle of your Node.js / Sails application.

Looking for the old repo? See the for-sails-0.12 branch of this repo or ryanc1256/sails-redis for examples of conventional adapters that let you use Redis to directly store and query records from your models.

This is an adapter for Sails versions 1.0 and up. If you are using an earlier version of Sails (or Waterline <v0.13), check out the for-sails-0.12 branch. Since this new release of sails-redis is more lightweight, and does not support the same semantic interface as its predecessor, be aware that there are breaking changes in your app when you upgrade. But I think you'll find that this new release is a great way to easily communicate with Redis, with minimal interference and a stable API. If you are interested in upgrading the new, Sails-v1-compatible release of this Redis adapter to support semantic usage (find, create, update, destroy), then please contact Mike or another core maintainer.

Usage

Install

Install is through NPM.

npm install sails-redis

Getting started

After installing and configuring this adapter (see below), you'll be able to use it to send commands to Redis from your Sails/Node.js app.

Here's an example demonstrating how to look up a cached value from Redis using async/await:

var util = require('util');

// Made up a fake parameter:
var key = 'foo';

// Inspired by https://github.com/node-machine/driver-interface/blob/06776813ff3a29cfa80c0011f3affa07bbc28698/layers/cache/get-cached-value.js
// Redis client docs: https://github.com/NodeRedis/node_redis/tree/v.2.8.0#sending-commands
// See also https://github.com/sailshq/machinepack-redis/blob/f0892e581286eac24757532513387162396356f7/machines/get-cached-value.js#L79-L94
// > If Redis returns `null`, then the value at this key is expired or does
// > not exist.  If a value _was_ found, attempt to JSON.parse() it.
// > (See `set-cached` for more info on why we're deserializing JSON here.)
var value = await sails.getDatastore('cache').leaseConnection(async (db)=>{
  var found = await (util.promisify(db.get).bind(db))(key);
  if (found === null) {
    return undefined;
  } else {
    return JSON.parse(found);
  }
});//¬

And here's another async/await example, this time showing how to set a value in Redis, along with a TTL (i.e. expiry):

var util = require('util');

// Made up some fake parameters:
var key = 'foo';
var value = {
  coolPhrase: `hello world, it's ${new Date()}`,
  iCan: ['put','w/e','I','want',4,'here']
};
var expiresIn = 1000*60*60*24;

// Convert `expiresIn` (which is expressed in milliseconds) to seconds,
// because unlike JavaScript, Redis likes to work with whole entire seconds.
var ttlInSeconds = Math.ceil(expiresIn / 1000);

// Inspired by https://github.com/node-machine/driver-interface/blob/06776813ff3a29cfa80c0011f3affa07bbc28698/layers/cache/cache-value.js
// Redis client docs: https://github.com/NodeRedis/node_redis/tree/v.2.8.0#sending-commands
// See also https://github.com/sailshq/machinepack-redis/blob/f0892e581286eac24757532513387162396356f7/machines/cache-value.js#L86-L107
// > Note: Redis expects string values, so we serialize `value` to JSON…
// > even if it is already a string.  (This is important for seamless reversibility.)
// > Also note that TTL is seconds, not ms…  I know it's weird -- sorry!
await sails.getDatastore('cache').leaseConnection(async (db)=>{
  await (util.promisify(db.setex).bind(db))(key, ttlInSeconds, JSON.stringify(value));
});//¬

Note that the leased connection (db) is just a Redis client instance. No need to connect it/bind event listeners-- it's already hot and ready to go. Any fatal, unexpected errors that would normally be emitted as the "error" event are handled by the underlying driver, and can be optionally handled with custom logic by providing a function for onUnexpectedFailure.

Need to use a different Redis client, like ioredis? Please have a look at the underlying driver for the latest info/discussion.

Using the Redis client instance

The documentation for the version of redis used in this adapter can be found here: https://github.com/NodeRedis/node_redis/tree/v.2.8.0#sending-commands

Configuration

This adapter supports standard datastore configuration, as well as some additional low-level options.

For example, in a Sails app, add the config below to your config/datastores.js file:

cache: {
  adapter: 'sails-redis',
  url: 'redis://localhost:6379',

  // Other available low-level options can also be configured here.
  // (see below for more information)
},

Note that you probably shouldn't set Redis as the default datastore for your application (your models wouldn't work!)

Low-Level Configuration (for redis client)

Configuration for the underlying Redis client itself is located as an object under the options. The following options are available:

  • parser: which Redis protocol reply parser to use. Defaults to hiredis if that module is installed. This may also be set to javascript.
  • return_buffers: defaults to false. If set to true, then all replies will be sent to callbacks as node Buffer objects instead of JavaScript Strings.
  • detect_buffers: default to false. If set to true, then replies will be sent to callbacks as node Buffer objects if any of the input arguments to the original command were Buffer objects. This option lets you switch between Buffers and Strings on a per-command basis, whereas return_buffers applies to every command on a client.
  • socket_nodelay: defaults to true. Whether to call setNoDelay() on the TCP stream, which disables the Nagle algorithm on the underlying socket. Setting this option to false can result in additional throughput at the cost of more latency. Most applications will want this set to true.
  • no_ready_check: defaults to false. When a connection is established to the Redis server, the server might still be loading the database from disk. While loading, the server not respond to any commands. To work around this, node_redis has a "ready check" which sends the INFO command to the server. The response from the INFO command indicates whether the server is ready for more commands. When ready, node_redis emits a ready event. Setting no_ready_check to true will inhibit this check.
  • enable_offline_queue: defaults to true. By default, if there is no active connection to the redis server, commands are added to a queue and are executed once the connection has been established. Setting enable_offline_queue to false will disable this feature and the callback will be execute immediately with an error, or an error will be thrown if no callback is specified.
  • retry_max_delay: defaults to null. By default every time the client tries to connect and fails time before reconnection (delay) almost doubles. This delay normally grows infinitely, but setting retry_max_delay limits delay to maximum value, provided in milliseconds.
  • connect_timeout defaults to false. By default client will try reconnecting until connected. Setting connect_timeout limits total time for client to reconnect. Value is provided in milliseconds and is counted once the disconnect occured.
  • max_attempts defaults to null. By default client will try reconnecting until connected. Setting max_attempts limits total amount of reconnects.
  • auth_pass defaults to null. By default client will try connecting without auth. If set, client will run redis auth command on connect.

Help

For more examples, or if you get stuck or have questions, click here.

Bugs   NPM version

To report a bug, click here.

Contributing   Build Status

Please observe the guidelines and conventions laid out in the Sails project contribution guide when opening issues or submitting pull requests.

NPM

Acknowledgements

I owe a big thank you to @ryanc1256 for all of his work with the original version of this adapter.

License

This adapter, like the Sails framework, is free and open-source under the MIT License.

More Repositories

1

sails

Realtime MVC Framework for Node.js
JavaScript
22,811
star
2

waterline

An adapter-based ORM for Node.js with support for mysql, mongo, postgres, mssql (SQL Server), and more
JavaScript
5,412
star
3

sails-docs

**Latest docs now live in the Sails core repo!** The source markdown files for the official Sails.js documentation, which gets compiled, squeezed, and stretched into HTML when we deploy the Sails website.
778
star
4

waterline-docs

WARNING: The content in this repo is out of date! See https://github.com/balderdashy/sails-docs for the most up-to-date documentation
452
star
5

sails-mongo

MongoDB adapter for Sails.js / Waterline ORM.
JavaScript
411
star
6

sails-mysql

MySQL adapter for Sails.js/Waterline
JavaScript
193
star
7

angularSails

AngularJS bindings for Sails. http://angularjs.org
JavaScript
184
star
8

sails.io.js

Browser SDK for communicating w/ Sails via sockets
JavaScript
182
star
9

sails-postgresql

PostgreSQL adapter for Sails.js
JavaScript
167
star
10

seed

A sample application generated by Sails.
JavaScript
91
star
11

mast

UI conventions built on top of Backbone.JS
JavaScript
81
star
12

sails-hook-email

Sails email hook
JavaScript
67
star
13

backbone-to-sails

Backbone SDK for communicating with Sails.js over Socket.io
JavaScript
64
star
14

skipper-s3

Streaming file uploads to S3
JavaScript
62
star
15

include-all

An easy way to include all files within a directory. Note: This is a fork of felixge's require-all which allows for optional includes.
JavaScript
56
star
16

sails-adapter-boilerplate

Example of a custom adapter (i.e. ORM plugin) for Waterline / Sails.js
JavaScript
45
star
17

sails-disk

Development-only persistent adapter for Sails.js / Waterline
JavaScript
44
star
18

captains-log

Lightweight logger with a simple pass-through configuration for use with fancier logging libraries. Used by the Sails framework. Optional support for colorized output, custom prefixes, and log levels (using npm's logging conventions.)
JavaScript
44
star
19

waterline-schema

This is the core schema builder used in the Waterline ORM.
JavaScript
33
star
20

activity-overlord-2-preview

A preview of Irl Nathan's Activity Overlord 2.0 (complete tutorial of Sails w/ Angular 1)
JavaScript
31
star
21

sails-generate

Master of ceremonies for generators in the Sails CLI
JavaScript
28
star
22

sails-generate-frontend

Generate the frontend part of a new Sails app.
JavaScript
26
star
23

sails-memory

In-memory, non-persistent adapter for Sails.js / Waterline
JavaScript
24
star
24

sails-hook-sockets

Implements socket.io support in Sails.
JavaScript
23
star
25

sails-hook-dev

A Sails hook that provides diagnostic / debugging information and levers during development.
JavaScript
22
star
26

sails-angular-seed

Boilerplate AngularJS app with Sails
JavaScript
21
star
27

enpeem

Lightweight wrapper for accessing npm programmatically (alternative to adding `npm` as a dependency)
JavaScript
19
star
28

sails-hook-orm

Implements support for Waterline ORM in Sails.
JavaScript
18
star
29

sails-hook-subapps

Sails hook for including child Sails apps into a parent app
JavaScript
18
star
30

sails-generate-generator

Generate a custom generator for Sails.js
JavaScript
18
star
31

merge-defaults

A recursive version of `_.defaults`.
JavaScript
16
star
32

waterline-adapter-tests

API integration tests for Waterline adapters
JavaScript
16
star
33

waterline-sequel

A SQL generator for use in Waterline Adapters
JavaScript
16
star
34

skipper-disk

Streaming file uploads to a server's local filesystem
JavaScript
14
star
35

sails-twitter

Twitter adapter for Sails.js
JavaScript
14
star
36

waterline-criteria

Utility library for use in Sails adapters where you need to filter a list of output using a criteria object
JavaScript
13
star
37

sails-generate-views-jade

Generate default views for a Sails app using Jade templates
HTML
11
star
38

billable

Tracks billable hours.
JavaScript
10
star
39

sails-generate-adapter

Generate a waterline/sails.js adapter.
JavaScript
10
star
40

fixture-stdout

A test fixture to intercept writes to stdout.
9
star
41

sails-generate-backend

Generate the backend part of a new Sails app.
JavaScript
9
star
42

sails-generate-new

Generate a new Sails app.
JavaScript
8
star
43

sails-riak

Riak adapter for Sails.js
CoffeeScript
7
star
44

machinepack-youtube

Communicate with the Youtube API to get video views, etc.
JavaScript
6
star
45

deretina

For supporting retina displays on the web: downsizes @2x images in the current directory
JavaScript
6
star
46

example-sails-proj-with-angular

JavaScript
6
star
47

sails-irc

IRC adapter for Sails.js
JavaScript
6
star
48

sails-generate-model

Generate a model in a Sails app.
JavaScript
5
star
49

sails-build-dictionary

DEPRECATED in Sails v1.0 (instead, just use [email protected] directly)
JavaScript
5
star
50

machinepack-slack

Use the Slack API from Node.js.
JavaScript
5
star
51

alcohol

Makes your dates prettier
4
star
52

sails-generate-api

API generator for Sails
JavaScript
4
star
53

booty

CoffeeScript
4
star
54

sails-util

Shared utilities between sails, waterline, etc.
JavaScript
4
star
55

sails-dirty

Sails.js adapter for @felixge's node-dirty
JavaScript
3
star
56

sails-elastic-search

Elastic Search Adapter for Sails JS
3
star
57

htassets

A mobile-compatible makeover for the default apache directory listing
JavaScript
3
star
58

Mobile-HTML-5-Video-Example

Cross-platform mobile video player using HTML 5
3
star
59

express-with-shared-mongo-session-example

An example of using a shared session in Express with MongoDB as the storage container
JavaScript
2
star
60

sails-generate-views

Generate default views for a Sails app
HTML
2
star
61

dev-workshop-conf

JavaScript
2
star
62

UserSwarm

JavaScript
2
star
63

sails-generate-controller

Generate a new controller file in an existing Sails app.
JavaScript
2
star
64

sails-generate-sails.io.js

Generate a sails.io.js browser SDK file at ./assets/js/dependencies/sails.io.js.
JavaScript
2
star
65

skipper-adapter-tests

Generic acceptance tests for Skipper adapters
JavaScript
1
star
66

waterline-cursor

Association/subquery helper
JavaScript
1
star
67

sails-generate-gruntfile

Generate gruntfile for a sails app.
JavaScript
1
star
68

stubble

A trimmed-down mustache.js for jQuery
JavaScript
1
star
69

sails-generate-hook

Generate a custom hook for Sails.js.
JavaScript
1
star
70

Naked

Chrome extension that opens links with stylesheets disabled for privacy.
1
star
71

sails-stringfile

translated/localized stringfiles containing messages from Sails core and dependencies
JavaScript
1
star
72

blueprint-api-example

An example of a Sails app using a blueprint API for use in "Run in Postman" buttons on the Sails website.
JavaScript
1
star
73

waterline-blob

Factory which generates waterline adapter definitions from blob definitions (eventually merge into waterline core)
JavaScript
1
star