sequelize-transparent-kache
v1.0.0-rc0
Published
Simple to use and universal cache layer for Sequelize
Downloads
1
Readme
sequelize-transparent-cache
Simple to use and universal cache layer for Sequelize.
- Abstract: does not depends on underlying database, or cache specific
- Transparent: objects returned from cache are regular Sequelize instances with all your methods
- Explicit: all calls to cache comes through
cache()
method - Lightweight: zero additional dependencies
Installation
Install sequelize-transparent-cache itself:
npm install --save sequelize-transparent-cache
Find and install appropriate adaptor for your cache system, see "Available adaptors" section below. In this example we will use ioredis
npm install --save sequelize-transparent-cache-ioredis
Example usage
PLEASE NOTE: there are differences in connecting this library with sequelize v3 and v4, regarding removed classMethods
and instanceMethods
support in v4.
Next example is for sequelize v4:
const Redis = require('ioredis')
const redis = new Redis()
const RedisAdaptor = require('sequelize-transparent-cache-ioredis')
const redisAdaptor = new RedisAdaptor({
client: redis,
namespace: 'model',
lifetime: 60 * 60
})
const sequelizeCache = require('sequelize-transparent-cache')
const { withCache } = sequelizeCache(redisAdaptor)
const Sequelize = require('sequelize')
const sequelize = new Sequelize('database', 'user', 'password', {
dialect: 'mysql',
host: 'localhost',
port: 3306
})
// Register and wrap your models:
// withCache() will add cache() methods to all models and instances in sequelize v4
const User = withCache(sequelize.import('./models/user'))
sequelize.sync()
.then(() => {
return User.cache().create({ // Create user in db and in cache
id: 1,
name: 'Daniel'
})
})
.then(() => {
return User.cache().findById(1) // Load user from cache
})
.then(user => {
return user.cache().update({ // Update in db and cache
name: 'Vikki'
})
})
Look for all examples applications in examples
folder.
Methods
Object returned by cache()
call contains wrappers for limited subset of sequelize model or instance methods.
Instance:
Model:
create()
findByPk()
findById()
upsert()
- EXPERIMENTALinsertOrUpdate()
- EXPERIMENTAL
In addition, both objects will contain client()
method to get cache adaptor.
Available adaptors
You can easy write your own adaptor. Each adatper must implement 3 methods:
get(path: Array): Promise<value>
set(path: Array, value: Object): Promise
del(path: Array): Promise
Checkout existed adaptors for reference implementation.