UNPKG

7.79 kBMarkdownView Raw
1<h1 align="center">
2 <img width="250" src="https://rawgit.com/lukechilds/keyv/master/media/logo.svg" alt="keyv">
3 <br>
4 <br>
5</h1>
6
7> Simple key-value storage with support for multiple backends
8
9[![Build Status](https://travis-ci.org/lukechilds/keyv.svg?branch=master)](https://travis-ci.org/lukechilds/keyv)
10[![Coverage Status](https://coveralls.io/repos/github/lukechilds/keyv/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/keyv?branch=master)
11[![npm](https://img.shields.io/npm/v/keyv.svg)](https://www.npmjs.com/package/keyv)
12
13Keyv provides a consistent interface for key-value storage across multiple backends via storage adapters. Supports TTL based expiry making it suitable as a cache or a persistent key-value store.
14
15## Features
16
17There are a few existing modules similar to Keyv, however none of them fulfilled all of my requirements. I created Keyv because I wanted something that:
18
19- Wasn't bloated
20- Had a simple Promise based API
21- Suitable as a TTL based cache or persistent key-value store
22- [Easily embeddable](#add-cache-support-to-your-module) inside another module
23- Works with any storage that implements the [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) API
24- Handles all JavaScript types (values can be `Buffer`/`null`/`undefined`)
25- Supports namespaces
26- Wide range of [**efficient, well tested**](#official-storage-adapters) storage adapters
27- Connection errors are passed through (db failures won't kill your app)
28- Supports the current active LTS version of Node.js or higher
29
30## Usage
31
32Install Keyv.
33
34```
35npm install --save keyv
36```
37
38By default everything is stored in memory, you can optionally also install a storage adapter.
39
40```
41npm install --save keyv-redis
42npm install --save keyv-mongo
43npm install --save keyv-sqlite
44npm install --save keyv-postgres
45npm install --save keyv-mysql
46```
47
48Create a new Keyv instance, passing your connection string if applicable. Keyv will automatically load the correct storage adapter.
49
50```js
51const Keyv = require('keyv');
52
53// One of the following
54const keyv = new Keyv();
55const keyv = new Keyv('redis://user:pass@localhost:6379');
56const keyv = new Keyv('mongodb://user:pass@localhost:27017/dbname');
57const keyv = new Keyv('sqlite://path/to/database.sqlite');
58const keyv = new Keyv('postgresql://user:pass@localhost:5432/dbname');
59const keyv = new Keyv('mysql://user:pass@localhost:3306/dbname');
60
61// Handle DB connection errors
62keyv.on('error' err => console.log('Connection Error', err));
63
64await keyv.set('foo', 'expires in 1 second', 1000); // true
65await keyv.set('foo', 'never expires'); // true
66await keyv.get('foo'); // 'never expires'
67await keyv.delete('foo'); // true
68await keyv.clear(); // undefined
69```
70
71### Namespaces
72
73You can namespace your Keyv instance to avoid key collisions and allow you to clear only a certain namespace while using the same database.
74
75```js
76const users = new Keyv('redis://user:pass@localhost:6379', { namespace: 'users' });
77const cache = new Keyv('redis://user:pass@localhost:6379', { namespace: 'cache' });
78
79await users.set('foo', 'users'); // true
80await cache.set('foo', 'cache'); // true
81await users.get('foo'); // 'users'
82await cache.get('foo'); // 'cache'
83await users.clear(); // undefined
84await users.get('foo'); // undefined
85await cache.get('foo'); // 'cache'
86```
87
88## Official Storage Adapters
89
90The official storage adapters are covered by over 150 integration tests to guarantee consistent behaviour. They are lightweight, efficient wrappers over the DB clients making use of indexes and native TTLs where available.
91
92Database | Adapter | Native TTL | Status
93---|---|---|---
94Redis | [keyv-redis](https://github.com/lukechilds/keyv-redis) | Yes | [![Build Status](https://travis-ci.org/lukechilds/keyv-redis.svg?branch=master)](https://travis-ci.org/lukechilds/keyv-redis)
95MongoDB | [keyv-mongo](https://github.com/lukechilds/keyv-mongo) | Yes | [![Build Status](https://travis-ci.org/lukechilds/keyv-mongo.svg?branch=master)](https://travis-ci.org/lukechilds/keyv-mongo)
96SQLite | [keyv-sqlite](https://github.com/lukechilds/keyv-sqlite) | No | [![Build Status](https://travis-ci.org/lukechilds/keyv-sqlite.svg?branch=master)](https://travis-ci.org/lukechilds/keyv-sqlite)
97PostgreSQL | [keyv-postgres](https://github.com/lukechilds/keyv-postgres) | No | [![Build Status](https://travis-ci.org/lukechilds/keyv-postgres.svg?branch=master)](https://travis-ci.org/lukechildskeyv-postgreskeyv)
98MySQL | [keyv-mysql](https://github.com/lukechilds/keyv-mysql) | No | [![Build Status](https://travis-ci.org/lukechilds/keyv-mysql.svg?branch=master)](https://travis-ci.org/lukechilds/keyv-mysql)
99
100## Third-party Storage Adapters
101
102You can also use third-party storage adapters or build your own. Keyv will wrap these storage adapters in TTL functionality and handle complex types internally.
103
104```js
105const Keyv = require('keyv');
106const myAdapter = require('./my-storage-adapter');
107
108const keyv = new Keyv({ store: myAdapter });
109```
110
111Any store that follows the [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) api will work.
112
113```js
114new Keyv({ store: new Map() });
115```
116
117For example, [`quick-lru`](https://github.com/sindresorhus/quick-lru) is a completely unrelated module that implements the Map API.
118
119```js
120const Keyv = require('keyv');
121const QuickLRU = require('quick-lru');
122
123const lru = new QuickLRU({ maxSize: 1000 });
124const keyv = new Keyv({ store: lru });
125```
126
127## Add Cache Support to your Module
128
129Keyv is designed to be easily embedded into other modules to add cache support. The recommended pattern is to expose a `cache` option in your modules options which is passed through to Keyv. Caching will work in memory by default and users have the option to also install a Keyv storage adapter and pass in a connection string.
130
131You should also set a namespace for your module so you can safely call `.clear()` without clearing unrelated app data.
132
133Inside your module:
134
135```js
136class AwesomeModule {
137 constructor(opts) {
138 this.cache = new Keyv(opts.cache, { namespace: 'awesome-module' });
139 }
140}
141```
142
143Now it can be consumed like this:
144
145```js
146const AwesomeModule = require('awesome-module');
147
148// Caches stuff in memory by default
149const awesomeModule = new AwesomeModule();
150
151// After npm install --save keyv-redis
152const awesomeModule = new AwesomeModule({ cache: 'redis://localhost' });
153```
154
155## API
156
157### new Keyv([uri], [options])
158
159Returns a new Keyv instance.
160
161The Keyv instance is also an `EventEmitter` that will emit an `'error'` event if the storage adapter connection fails.
162
163### uri
164
165Type: `String`<br>
166Default: `undefined`
167
168The connection string URI.
169
170Merged into the options object as options.uri.
171
172### options
173
174Type: `Object`
175
176The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options.
177
178#### options.namespace
179
180Type: `String`<br>
181Default: `'keyv'`
182
183Namespace for the current instance.
184
185#### options.ttl
186
187Type: `Number`<br>
188Default: `undefined`
189
190Default TTL. Can be overridden by specififying a TTL on `.set()`.
191
192#### options.store
193
194Type: `Storage adapter instance`<br>
195Default: `new Map()`
196
197The storage adapter instance to be used by Keyv.
198
199#### options.adapter
200
201Type: `String`<br>
202Default: `undefined`
203
204Specify an adapter to use. e.g `'redis'` or `'mongodb'`.
205
206### Instance
207
208Keys must always be strings. Values can be of any type.
209
210#### .set(key, value, [ttl])
211
212Set a value.
213
214By default keys are persistent. You can set an expiry TTL in milliseconds.
215
216Returns `true`.
217
218#### .get(key)
219
220Returns the value.
221
222#### .delete(key)
223
224Deletes an entry.
225
226Returns `true` if the key existed, `false` if not.
227
228#### .clear()
229
230Delete all entries in the current namespace.
231
232Returns `undefined`.
233
234## License
235
236MIT © Luke Childs