sequelize-simple-cache
Advanced tools
Comparing version 1.1.4 to 1.2.0
{ | ||
"name": "sequelize-simple-cache", | ||
"version": "1.1.4", | ||
"version": "1.2.0", | ||
"description": "A simple, transparent, client-side, in-memory cache for Sequelize", | ||
"main": "src/SequelizeSimpleCache.js", | ||
"main": "src/index.js", | ||
"types": "src/index.d.ts", | ||
"author": "Frank Thelen", | ||
@@ -21,6 +22,10 @@ "license": "MIT", | ||
"lint": "eslint . --ignore-path ./.eslintignore", | ||
"test": "NODE_ENV=test nyc --reporter=lcov --reporter=text-summary mocha --exit --recursive --timeout 2000 test/unit", | ||
"itest": "NODE_ENV=itest mocha --exit --recursive --timeout 60000 test/integration", | ||
"test": "npm run lint && npm run test:unit && npm run test:integration:sqlite && npm run test:typescript", | ||
"test:unit": "nyc --reporter=lcov --reporter=text-summary mocha --exit --recursive --timeout 2000 test/unit/**/*.js", | ||
"test:integration": "npm run test:integration:sqlite && npm run test:integration:postgres", | ||
"test:integration:postgres": "mocha --exit --recursive --timeout 60000 test/integration/integration.postgres.spec.js", | ||
"test:integration:sqlite": "mocha --exit --recursive --timeout 60000 test/integration/integration.sqlite.spec.js", | ||
"test:typescript": "mocha -r ts-node/register test/typescript/**/*.spec.ts", | ||
"coveralls": "nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls", | ||
"preversion": "npm run lint && npm run test && npm run itest" | ||
"preversion": "npm run lint && npm run test:unit && npm run test:integration && npm run test:typescript" | ||
}, | ||
@@ -34,2 +39,6 @@ "engines": { | ||
"devDependencies": { | ||
"@types/chai": "^4.2.14", | ||
"@types/mocha": "^8.2.0", | ||
"@types/node": "^14.14.20", | ||
"@types/validator": "^13.1.2", | ||
"babel-eslint": "^10.1.0", | ||
@@ -39,3 +48,3 @@ "chai": "^4.2.0", | ||
"coveralls": "^3.1.0", | ||
"eslint": "^7.16.0", | ||
"eslint": "^7.17.0", | ||
"eslint-config-airbnb-base": "^14.2.1", | ||
@@ -48,7 +57,9 @@ "eslint-plugin-import": "^2.22.1", | ||
"pg": "^8.5.1", | ||
"pg-promise": "^10.8.6", | ||
"pg-promise": "^10.8.7", | ||
"sequelize": "^6.3.5", | ||
"sinon": "^9.2.2", | ||
"sinon": "^9.2.3", | ||
"sinon-chai": "^3.5.0", | ||
"sqlite3": "^5.0.0" | ||
"sqlite3": "^5.0.1", | ||
"ts-node": "^9.1.1", | ||
"typescript": "^4.1.3" | ||
}, | ||
@@ -55,0 +66,0 @@ "dependencies": { |
@@ -14,2 +14,3 @@ # sequelize-simple-cache | ||
[![code style](https://img.shields.io/badge/code_style-airbnb-brightgreen.svg)](https://github.com/airbnb/javascript) | ||
[![Types](https://img.shields.io/npm/types/sequelize-simple-cache.svg)](https://www.npmjs.com/package/sequelize-simple-cache) | ||
[![License Status](http://img.shields.io/npm/l/sequelize-simple-cache.svg)]() | ||
@@ -52,3 +53,3 @@ | ||
// initialize cache | ||
// create cache -- referring to Sequelize models by name, e.g., `User` | ||
const cache = new SequelizeSimpleCache({ | ||
@@ -71,3 +72,3 @@ User: { ttl: 5 * 60 }, // 5 minutes | ||
// first time resolved from database, subsequent times from local cache. | ||
const fred = User.findOne({ where: { username: 'fred' }}); | ||
const fred = await User.findOne({ where: { name: 'fred' }}); | ||
``` | ||
@@ -83,2 +84,8 @@ | ||
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 | ||
@@ -103,3 +110,3 @@ | ||
// if you don't want a query to be cached, you may explicitly bypass the cache like this | ||
Model.noCache().findAll(...); | ||
Model.noCache().findAll(/* ... */); | ||
// transactions enforce bypassing the cache, e.g.: | ||
@@ -129,3 +136,3 @@ Model.findOne({ where: { name: 'foo' }, transaction: t, lock: true }); | ||
```javascript | ||
const cache = new SequelizeSimpleCache({...}); | ||
const cache = new SequelizeSimpleCache({ /* ... */ }); | ||
// clear all | ||
@@ -161,3 +168,3 @@ cache.clear(); | ||
```javascript | ||
Model.noCache().findOne(...); | ||
Model.noCache().findOne(/* ... */); | ||
``` | ||
@@ -217,3 +224,3 @@ | ||
// initializing the cache | ||
const cache = useCache ? new SequelizeSimpleCache({...}) : undefined; | ||
const cache = useCache ? new SequelizeSimpleCache({/* ... */}) : undefined; | ||
// loading the models | ||
@@ -223,1 +230,50 @@ const model = require('./models/model')(sequelize); | ||
``` | ||
## TypeScript Support | ||
`SequelizeSimpleCache` includes type definitions for TypeScript. | ||
They are based on the [Sequelize types](https://sequelize.org/master/manual/typescript.html). | ||
For this module to work, your **TypeScript compiler options** must include | ||
`"target": "ES2015"` (or later), `"moduleResolution": "node"`, and | ||
`"esModuleInterop": true`. | ||
Please note that -- for the sake of good typing -- the interface of `new SequelizeSimpleCache()` | ||
had to be changed slightly. | ||
A quick example: | ||
```typescript | ||
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([{ | ||
name: 'User', ttl: 5 * 60, // 5 minutes | ||
}, { | ||
name: 'Page', // 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' }}); | ||
``` |
@@ -20,3 +20,6 @@ const md5 = require('md5'); | ||
}; | ||
this.config = Object.entries(config) | ||
const configHash = Array.isArray(config) // alternative interface for TypeScript | ||
? config.reduce((acc, { name, ...rest }) => ({ ...acc, [name]: rest }), {}) | ||
: config; | ||
this.config = Object.entries(configHash) | ||
.reduce((acc, [type, { | ||
@@ -23,0 +26,0 @@ ttl = defaults.ttl, |
@@ -32,2 +32,6 @@ const sinon = require('sinon'); | ||
it('should create cache without crashing / empty args / 1 / config array', () => { | ||
expect(() => new SequelizeSimpleCache([], {})).to.not.throw(); | ||
}); | ||
it('should create cache without crashing / empty args / 2', () => { | ||
@@ -41,2 +45,6 @@ expect(() => new SequelizeSimpleCache({}, { ops: false })).to.not.throw(); | ||
it('should create cache without crashing / dummy model / config array', () => { | ||
expect(() => new SequelizeSimpleCache([{ name: 'User' }], { ops: false })).to.not.throw(); | ||
}); | ||
it('should generate unique hashes for Sequelize queries with ES6 symbols and functions', () => { | ||
@@ -72,3 +80,3 @@ const queries = [{ | ||
it('should create decorations on model / cached', async () => { | ||
it('should create decorations on model / cached / config array', async () => { | ||
const stub = sinon.stub().resolves({ username: 'fred' }); | ||
@@ -79,3 +87,3 @@ const model = { | ||
}; | ||
const cache = new SequelizeSimpleCache({ User: {} }, { ops: false }); | ||
const cache = new SequelizeSimpleCache([{ name: 'User' }], { ops: false }); | ||
const User = cache.init(model); | ||
@@ -207,3 +215,3 @@ expect(User.noCache).to.be.a('function'); | ||
it('should cache but expire after ttl', async () => { | ||
it('should cache but expire after ttl / config array', async () => { | ||
const stub = sinon.stub().resolves({ username: 'fred' }); | ||
@@ -214,3 +222,3 @@ const model = { | ||
}; | ||
const cache = new SequelizeSimpleCache({ User: { ttl: 1 } }, { ops: false }); | ||
const cache = new SequelizeSimpleCache([{ name: 'User', ttl: 1 }], { ops: false }); | ||
const User = cache.init(model); | ||
@@ -227,3 +235,3 @@ const result1 = await User.findOne({ where: { username: 'fred' } }); | ||
it('should cache forever', async () => { | ||
it('should cache forever / config array', async () => { | ||
const stub = sinon.stub().resolves({ username: 'fred' }); | ||
@@ -234,3 +242,3 @@ const model = { | ||
}; | ||
const cache = new SequelizeSimpleCache({ User: { ttl: false } }, { ops: false }); | ||
const cache = new SequelizeSimpleCache([{ name: 'User', ttl: false }], { ops: false }); | ||
const User = cache.init(model); | ||
@@ -237,0 +245,0 @@ const result1 = await User.findOne({ where: { username: 'fred' } }); |
{ | ||
"compilerOptions": { | ||
"outDir": "src", | ||
"declaration": true, | ||
"emitDeclarationOnly": true, | ||
/* Visit https://aka.ms/tsconfig.json to read more about this file */ | ||
/* Basic Options */ | ||
// "incremental": true, /* Enable incremental compilation */ | ||
// "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ | ||
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ | ||
// "lib": [], /* Specify library files to be included in the compilation. */ | ||
"allowJs": true, /* Allow javascript files to be compiled. */ | ||
// "checkJs": true, /* Report errors in .js files. */ | ||
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ | ||
// "declaration": true, /* Generates corresponding '.d.ts' file. */ | ||
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ | ||
// "sourceMap": true, /* Generates corresponding '.map' file. */ | ||
// "outFile": "./", /* Concatenate and emit output to single file. */ | ||
// "outDir": "./", /* Redirect output structure to the directory. */ | ||
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ | ||
// "composite": true, /* Enable project compilation */ | ||
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ | ||
// "removeComments": true, /* Do not emit comments to output. */ | ||
// "noEmit": true, /* Do not emit outputs. */ | ||
// "importHelpers": true, /* Import emit helpers from 'tslib'. */ | ||
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ | ||
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ | ||
/* Strict Type-Checking Options */ | ||
// "strict": true, /* Enable all strict type-checking options. */ | ||
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ | ||
// "strictNullChecks": true, /* Enable strict null checks. */ | ||
// "strictFunctionTypes": true, /* Enable strict checking of function types. */ | ||
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ | ||
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ | ||
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ | ||
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ | ||
/* Additional Checks */ | ||
// "noUnusedLocals": true, /* Report errors on unused locals. */ | ||
// "noUnusedParameters": true, /* Report errors on unused parameters. */ | ||
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ | ||
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ | ||
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ | ||
/* Module Resolution Options */ | ||
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ | ||
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ | ||
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ | ||
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ | ||
// "typeRoots": [], /* List of folders to include type definitions from. */ | ||
// "types": [], /* Type declaration files to be included in compilation. */ | ||
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ | ||
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ | ||
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ | ||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ | ||
/* Source Map Options */ | ||
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ | ||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ | ||
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ | ||
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ | ||
/* Experimental Options */ | ||
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ | ||
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ | ||
/* Advanced Options */ | ||
// "skipLibCheck": true, /* Skip type checking of declaration files. */ | ||
// "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ | ||
}, | ||
"include": ["src/**.*"], | ||
"exclude": [] | ||
"target": "ES2015", /* 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ | ||
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ | ||
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ | ||
} | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
52479
19
1027
271
23