Code Monkey home page Code Monkey logo

sequelize-simple-cache's Introduction

sequelize-simple-cache

This is a simple, transparent, client-side, in-memory cache for Sequelize. Cache invalidation is based on time-to-live (ttl). Selectively add your Sequelize models to the cache. Works with all storage engines supported by Sequelize.

main workflow Coverage Status Dependencies Status Maintainability node code style Types License Status

This cache might work for you if you have database tables that (1) are frequently read but very rarely written and (2) contain only few rows of data.

In a project, we had a couple of database tables with a sort of configuration. Something like 4 or 5 tables with some 10 rows of data. Nearly every request needed this data, i.e., it was read all the time. But updated only very rarely, e.g, once a day. So, pre-fetching or simple in-memory caching would work for us.

If that's not matching your scenario, better look for something more sophisticated such as Redis or Memcached.

Tested with

  • Sequelize 6, Node 12/14/15, integration tested with Postgres 11/12 (via pg 8) and sqlite3 v5 (memory)
  • Sequelize 5, Node 10/12/13, integration tested with Postgres 10/11 (via pg 7) and sqlite3 v4 (memory)

Install

npm install sequelize-simple-cache

Usage

Setup the cache along with loading your Sequelize models like this:

const Sequelize = require('sequelize');
const SequelizeSimpleCache = require('sequelize-simple-cache');

// create db connection
const sequelize = new Sequelize('database', 'username', 'password', { ... });

// create cache -- referring to Sequelize models by name, e.g., `User`
const cache = new SequelizeSimpleCache({
  User: { ttl: 5 * 60 }, // 5 minutes
  Page: { }, // default ttl is 1 hour
});

// assuming you have your models in separate files with "model definers"
// -- e.g, see below or https://github.com/sequelize/express-example --
// add your models to the cache like this
const User = cache.init(require('./models/user')(sequelize));
const Page = cache.init(require('./models/page')(sequelize));

// no caching for this one (because it's not configured to be cached)
// will only add dummy decorators to the model for a homogeneous interface to all models
const Order = cache.init(require('./models/order')(sequelize));

// the Sequelize model API is fully transparent, no need to change anything.
// first time resolved from database, subsequent times from local cache.
const fred = await User.findOne({ where: { name: 'fred' }});

./models/user.js might look like this:

const { Model } = require('sequelize');
class User extends Model {}
module.exports = (sequelize) => User.init({ /* attributes */ }, { sequelize });

Please note that SequelizeSimpleCache refers to Sequelize models by name. The model name is usually equals the class name (e.g., class User extends Model {} β†’ User). Unless it is specified differently in the model options' modelName property (e.g., User.init({ /* attributes */ }, { sequelize, modelName: 'Foo' }) β†’ Foo). The same is true if you are using sequelize.define() to define your models.

More Details

Supported methods

The following methods on Sequelize model instances are supported for caching: findOne, findAndCountAll, findByPk, findAll, count, min, max, sum. In addition, for Sequelize v4: find, findAndCount, findById, findByPrimary, all.

Non-cacheable queries / bypass caching

You need to avoid non-cacheable queries, e.g., queries containing dynamic timestamps.

const { Op, fn } = require('sequelize');
// this is not good
Model.findAll({ where: { startDate: { [Op.lte]: new Date() }, } });
// you should do it this way
Model.findAll({ where: { startDate: { [Op.lte]: fn('NOW') }, } });
// if you don't want a query to be cached, you may explicitly bypass the cache like this
Model.noCache().findAll(/* ... */);
// transactions enforce bypassing the cache, e.g.:
Model.findOne({ where: { name: 'foo' }, transaction: t, lock: true });

Time-to-live (ttl)

Each model has its individual time-to-live (ttl), i.e., all database requests on a model are cached for a particular number of seconds. Default is one hour. For eternal caching, i.e., no automatic cache invalidation, simply set the model's ttl to false (or any number less or equals 0).

const cache = new SequelizeSimpleCache({
  User: { ttl: 5 * 60 }, // 5 minutes
  Page: { }, // default ttl is 1 hour
  Foo: { ttl: false } // cache forever
});

Clear cache

There are these ways to clear the cache.

const cache = new SequelizeSimpleCache({ /* ... */ });
// clear all
cache.clear();
// clear all entries of specific models
cache.clear('User', 'Page');
// or do the same on any model
Model.clearCache(); // only model
Model.clearCacheAll(); // entire cache

By default, the model's cache is automatically cleared if these methods are called: update, create, upsert, destroy, findOrBuild. In addition, for Sequelize v4: insertOrUpdate, findOrInitialize, updateAttributes.

You can change this default behavior like this:

const cache = new SequelizeSimpleCache({
  User: { }, // default clearOnUpdate is true
  Page: { clearOnUpdate: false },
});

If you run multiple instances (clients or containers or PODs or alike), be aware that cache invalidation is more complex that the above simple approach.

Bypass caching

Caching can explicitly be bypassed like this:

Model.noCache().findOne(/* ... */);

Limit

This cache is meant as a simple in-memory cache for a very limited amount of data. So, you should be able to control the size of the cache.

const cache = new SequelizeSimpleCache({
  User: { }, // default limit is 50
  Page: { limit: 30 },
});

Logging

There is "debug" and "ops" logging -- both are off by default. Logging goes to console.debug() unless you set delegate to log somewhere else. event is one of: init, hit, miss, load, purge or ops.

const cache = new SequelizeSimpleCache({
  // ...
}, {
  debug: true,
  ops: 60, // seconds
  delegate: (event, details) => { ... },
});

Unit testing

If you are mocking your Sequelize models in unit tests with Sinon et al., caching might be somewhat counterproductive. So, either clear the cache as needed in your unit tests. For example (using mocha):

describe('My Test Suite', () => {
  beforeEach(() => {
    Model.clearCacheAll(); // on any model with the same effect
  });
  // ...

Or disable the cache right from the beginning. A quick idea... have a specific config value in your project's /config/default.js and /config/test.js to enable or disable the cache respectively. And start your unit tests with setting NODE_ENV=test before. This is actually the way I am doing it; plus a few extra unit tests for caching.

const config = require('config');
const useCache = config.get('database.cache');
// initializing the cache
const cache = useCache ? new SequelizeSimpleCache({/* ... */}) : undefined;
// loading the models
const model = require('./models/model')(sequelize);
const Model = useCache ? cache.init(model) : model;

TypeScript Support

SequelizeSimpleCache includes type definitions for TypeScript. They are based on the Sequelize types.

For this module to work, your TypeScript compiler options must include "target": "ES2015" (or later), "moduleResolution": "node", and "esModuleInterop": true.

A quick example:

import { Sequelize, Model, DataTypes } from "sequelize";
import SequelizeSimpleCache from "sequelize-simple-cache";

interface UserAttributes {
  id: number;
  name: string;
}

class User extends Model<UserAttributes> implements UserAttributes {
  public id!: number;
  public name!: string;
}

// create db connection
const sequelize = new Sequelize(/* ... */);

// initialize models
User.init({ /* attributes */ }, { sequelize, tableName: 'users' });

// create cache -- referring to Sequelize models by name, e.g., `User`
const cache = new SequelizeSimpleCache({
  [User.name]: { ttl: 5 * 60 }, // 5 minutes
  'Foo': {}, // default ttl is 1 hour
});

// add User model to the cache
const UserCached = cache.init<User>(User);

// the Sequelize model API is fully transparent, no need to change anything.
// first time resolved from database, subsequent times from local cache.
const fred = await UserCached.findOne({ where: { name: 'fred' }});

sequelize-simple-cache's People

Contributors

frankthelen avatar shurik239 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

sequelize-simple-cache's Issues

Explicit cache invalidation

In my case we are using a single node (it's actually an embedded process) so other parts of the code know explicitly when models are updated. Is there a way to invalidate certain model/ids when an update occurs?

add cache Tag

there is a problem when we try to recache , it has not any tag so if i update my model it changes for everyone so other users need cache again you can add a specific id for cache Model . what do you say ?
thank you.
for example we user 1 and 2 .

user 1 updates his profile because it is not using specific tag for cache Model . it is doing the same for the user 2.

sequelize.import is deprecated

sequelize.import is deprecated in sequelize@6

Now I'm getting error: TypeError: sequelize.import is not a function

Sequelize document says, we should use require instead. How can we use it here?

Queries with transaction not bypassing cache

If a database query specifies a transaction, e.g.,

User.findOne({
   where: { username: 'fred' },
   transaction: t,
   lock: true,
});

...caching does not make sense whatsoever.
Queries with transaction should bypass caching completely.

An in-range update of eslint is breaking the build 🚨

The devDependency eslint was updated from 5.15.3 to 5.16.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v5.16.0
  • dfef227 Build: gensite passes rulesMeta to formatter rendering (#11567) (Kevin Partington)
  • c06d38c Fix: Allow HTML formatter to handle no meta data (#11566) (Ilya Volodin)
  • 87a5c03 Docs: func-style: clarify when allowArrowFunctions is used (#11548) (Oliver Joseph Ash)
  • bc3e427 Update: pass rule meta to formatters RFC 10 (#11551) (Chris Meyer)
  • b452f27 Chore: Update README to pull in reviewer data (#11506) (Nicholas C. Zakas)
  • afe3d25 Upgrade: Bump js-yaml dependency to fix Denial of Service vulnerability (#11550) (Vernon de Goede)
  • 4fe7eb7 Chore: use nyc instead of istanbul (#11532) (Toru Nagashima)
  • f16af43 Chore: fix formatters/table test (#11534) (Toru Nagashima)
  • 78358a8 Docs: fix duplicate punctuation in CLI docs (#11528) (Teddy Katz)
Commits

The new version differs by 11 commits.

  • ded2f94 5.16.0
  • ea36e13 Build: changelog update for 5.16.0
  • dfef227 Build: gensite passes rulesMeta to formatter rendering (#11567)
  • c06d38c Fix: Allow HTML formatter to handle no meta data (#11566)
  • 87a5c03 Docs: func-style: clarify when allowArrowFunctions is used (#11548)
  • bc3e427 Update: pass rule meta to formatters RFC 10 (#11551)
  • b452f27 Chore: Update README to pull in reviewer data (#11506)
  • afe3d25 Upgrade: Bump js-yaml dependency to fix Denial of Service vulnerability (#11550)
  • 4fe7eb7 Chore: use nyc instead of istanbul (#11532)
  • f16af43 Chore: fix formatters/table test (#11534)
  • 78358a8 Docs: fix duplicate punctuation in CLI docs (#11528)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

cache deleting automatically even after ttl:false

I did this in my dal layer file
` const cache = new SequelizeSimpleCache({
License: { ttl: false }, // cache for 1 day
}, {
debug: true,
ops: 60, // seconds

});

let checkConnection = async function () {
try {
await sequelize.authenticate();
} catch (error) {
logger.error("Unable to connect to the database:", error);
throw error;
}
}; `

and the function is also in dal layer file only...

let getAllLicenses = async function () { let licenses = await LicenseCache.findAll(); return licenses; };

but. the cache initializes
CACHE INIT { type: 'License', ttl: false, methods: [ 'findOne', 'findAndCountAll', 'findByPk', 'findAll', 'count', 'min', 'max', 'sum', 'find', 'findAndCount', 'findById', 'findByPrimary', 'all' ], methodsUpdate: [ 'create', 'bulkCreate', 'update', 'destroy', 'upsert', 'findOrBuild', 'insertOrUpdate', 'findOrInitialize', 'updateAttributes' ], limit: 50, clearOnUpdate: true, hit: 0, miss: 0, load: 0, purge: 0, ratio: NaN, size: { License: 0 } }

when i first call it it is a miss obviously and then it stores the data in cahce
CACHE OPS { hit: 4, miss: 6, load: 6, purge: 0, ratio: 0.4, size: { License: 6 } }

but then after a few seconds it cleans the cache
CACHE OPS { hit: 0, miss: 0, load: 0, purge: 0, ratio: NaN, size: { License: 0 } }

but ttl is false so cache should not be deleted

Trying to cache one model, does not work

Hello, I'm trying to cache just one model, but when I set everything up no logs come up, neither do errors. I can query all normally but I seen no logs with regards to caching.

This is how my setup code looks like:

const cache = new SequelizeSimpleCache({
  DataStream: {ttl: 60*60} // 1 hour TTL
});

const Project = ProjectModel(sequelize);
const Measurement = MeasurementModel(sequelize);

//const DataStreamSeq = DataStreamModel(sequelize); // tried init both ways
//const DataStream = cache.init(DataStreamSeq);
const DataStream = cache.init(sequelize.import('./models/dataStream'));


const DataPoint = DataPointModel(sequelize, DataStream);

module.exports = {
  Project,
  Measurement,
  DataStream,
  DataPoint,
  sequelize
};

And my DataStream model definition looks something like this:

class DataStream extends Model {
  get objectId() {
    return {id: this.id};
  }
};

module.exports = (sequelize) => {
  DataStream.init({
    ...
     });
  return DataStream;
};

Versions I'm using: "sequelize": "^5.21.2", "sequelize-simple-cache": "^1.0.4".

Thanks for any insight :)

Problem with cache initiation

I'm following the instructions provided and initiate the cache while defining my models:

// --- models/index.js ---

const SequelizeSimpleCache = require(`sequelize-simple-cache`);

const defineCategory = require(`./category`);
const defineComment = require(`./comment`);
const defineArticle = require(`./article`);
const defineArticleCategory = require(`./article-category`);
const Aliase = require(`./aliase`);

const cache = new SequelizeSimpleCache({
  Article: {ttl: false}, // cache forever
  Category: {ttl: false},
  Comment: {ttl: false}
}, {
  debug: true,
  ops: 10,
});

module.exports = (sequelize) => {
  const Category = defineCategory(sequelize);
  const Comment = defineComment(sequelize);
  const Article = defineArticle(sequelize);
  const ArticleCategory = defineArticleCategory(sequelize);

  cache.init(Category);
  cache.init(Comment);
  cache.init(Article);

  Article.hasMany(Comment, {as: Aliase.COMMENTS, foreignKey: `articleId`});
  Comment.belongsTo(Article, {as: Aliase.ARTICLE, foreignKey: `articleId`});
  
  ...

  return {Category, Comment, Article, ArticleCategory};
};

Each model is located in a separate module and is defined via class:

// --- models/category.js ---

const {DataTypes, Model} = require(`sequelize`);

class Category extends Model {}

module.exports = (sequelize) => Category.init({
  name: {
    type: DataTypes.STRING,
    allowNull: false
  }
}, {
  sequelize,
  modelName: `Category`,
  tableName: `categories`
});

When I start my server, the cache seems to accept my models:

CACHE INIT {
  type: 'Category',
  ttl: false,
  methods: [
    'findOne',  'findAndCountAll',
    'findByPk', 'findAll',
    'count',    'min',
    'max',      'sum',
    'find',     'findAndCount',
    'findById', 'findByPrimary',
    'all'
  ],
  methodsUpdate: [
    'create',
    'bulkCreate',
    'update',
    'destroy',
    'upsert',
    'findOrBuild',
    'insertOrUpdate',
    'findOrInitialize',
    'updateAttributes'
  ],
  limit: 50,
  clearOnUpdate: true,
  hit: 0,
  miss: 0,
  load: 0,
  purge: 0,
  ratio: NaN,
  size: { Category: 0 }
}

But while using app in dev mode the cache debug console remains the same:

CACHE OPS {
  hit: 0,
  miss: 0,
  load: 0,
  purge: 0,
  ratio: NaN,
  size: { Category: 0, Comment: 0, Article: 0 }
}

I assume the size key refers to the cached instances, but it's empty despite any queries made to DB.

I have tried to initiate cache just after my models are defined and before they are filled with mock data, the result is the same.
What am I doing wrong?

An in-range update of sequelize is breaking the build 🚨

The devDependency sequelize was updated from 5.2.6 to 5.2.7.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

sequelize is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v5.2.7

5.2.7 (2019-03-30)

Bug Fixes

Commits

The new version differs by 5 commits.

  • a676eea fix(typings): upsert options (#10655)
  • ea5afbf fix(model): map fields only once when saving (#10658)
  • 33e140d docs: fix typos (#10656)
  • 580c065 test: typos in model test names (#10659)
  • 46e0f68 docs: fix typo in belongs-to-many.js (#10652)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.