A simple caching object data base on ES6 Map() that support auto invalidate cache when reach maximum size. This'll work if all object you wanna cache have a unique key
like when you cache user data, all object have a key
like userID
npm i js-simple-cache
// v1.0.7
const Cache = require('js-simple-cache')
const cache = new Cache('userID', 10000)
// v1.2.0
// Node module
const { Cache } = require('js-simple-cache')
const cache = new Cache('userID', 10000)
// ES module
import { Cache } from 'js-simple-cache'
const cache = new Cache('userID', 10000)
- First aggrument is unique
key
, when youset
new item, it auto set with thatkey
for you and you can access later withget
- Second arrgrument is limit size, it help cache to auto delete least use when cache reach maximum size limit (but you can set undefined to have no limit)
- Note: This only accept cache object has a props that you provide when init
- Getter only: key, size
- Getter and Setter: limit (Integer and greater than current size)
- First aggrument is the object that contain
key
, second aggrument is a timer (miliseconds) that will help you auto remove item afterX
miliseconds.
cache.set({userID:1, username: 'HOAI AN'}, 10000) // item will auto remove after 10 seconds
- This is base on ES6 Map so if you put same key it gonna replace old item
const user = cache.get(1)
console.log(user) // {userID:1, username: 'HOAI AN'}
- If you using typescript and you cache object create by a class, you can casting like by using
as
like this.
const order = cache.get(110230) as Order // Order is your class
cache.remove(1)
cache.clear()
cache.set({ userID: 1, username: 'HOAI AN' })
cache.set({ userID: 2, username: 'HOAI AN1' })
cache.set({ userID: 3, username: 'HOAI AN2' })
cache.set({ userID: 4, username: 'HOAI AN3' })
cache.set({ userID: 5, username: 'HOAI AN4' })
cache.set({ userID: 6, username: 'HOAI AN5' })
const key = cache.findKey(item => item.username === 'HOAI AN3')
console.log(key) // 4
cache.has(2)
const key = cache.filter(item => item.username.includes('HOAIAN'))
- You can convert to Object / Array to use other prototype
const options = {
searchValue: 'string',
searchFields: ['field1', 'field2'], // specified object field to search ( if you have nested object or array, enable deepScan)
nocase: true, // optional set true to match whatever
deepScan: true // optional set true to enable nested object scan
}
const result = cache.search(options)
cache.toArray()
cache.toObject()
- If you export to Object, it gonna use your
key
values when you create cache askey
for Object
cache.toJSONArray()
cache.toJSONObject()