1.0.0 • Published 4 years ago

@lexriver/cache v1.0.0

Weekly downloads
1
License
MIT
Repository
github
Last release
4 years ago

Cache

This package provides

  • BoxedValue<T>
  • CachedVariable<T>
  • CachedMap<K,V>

for caching your data.

Install

npm install @lexriver/cache

CachedVariable<T>

    const myCachedVariable = new CachedVariable<string>(options)

where options is an object of type:

{
    maxAgeInMilliseconds:number, 
    updateFunction:(prevValue?:T)=>Promise<T>|T, 
    initialValue?:T
    useLazyUpdate?:boolean
}
  • maxAgeInMilliseconds:number is a timeout before updating the value
  • updateFunction:(prevValue?:T)=>Promise<T>|T is a function that will be executed to update value
  • initialValue?:T is a initial value, default is undefined
  • useLazyUpdate?:boolean if true then stale value will be updated only on getAsync() method

Example

    const myCachedVariable = new CachedVariable<string>({
        maxAgeInMilliseconds:5000, 
        updateFunction:(prevValue:string)=>{
            return prevValue+'+'
        } 
        initialValue:'default value'
    })

setUpdateFunction(updateFunctionAsync:(prevValue?:T)=>Promise<T>|T)

Change the update function

    myCachedVariable.setUpdateFunction((prevValue:string)=>prevValue+'!')

async getAsync():Promise<T>

Returns cached value if possible or executes updateFunctionAsync to get a new value

    await myCachedVariable.getAsync()

async updateWithValueAsync(value:T)

Set new value

    await myCachedVariable.updateWithValueAsync('my new value')

async clearCacheAsync()

Remove any existing value from cache

    await myCachedVariable.clearCacheAsync()

hasValue:boolean

Check if there is some value in cache

    if(myCachedVariable.hasValue) {...}

onDisposeEvent:TypeEvent<()=>void>

Event that triggers when clearCacheAsync() is executed

    myCachedVariable.onDisposeEvent.subscribe(() => {
        console.log('myCachedVariable is empty')
    })

CachedMap<K,V>

    const myCachedMap = new CachedMap<K, V>(options)

K is a type for key, and V is a value type.

K can be number, boolean, string, Object, or interface

options is an object of type:

{
    maxAgeInMilliseconds:number, 
    updateFunction:(key:K)=>Promise<V>|V, 
    useLazyUpdate?:boolean
}
  • maxAgeInMilliseconds:number is a timeout before updating the value
  • updateFunction:(key:K)=>Promise<V>|V is a function that will be executed to update value
  • useLazyUpdate?:boolean if true then stale value will be updated only on getAsync() method

Example

interface MyInterface{
    text:string
}
let myCachedMap2 = new CachedMap<MyInterface, number>({
    maxAgeInMilliseconds: 100*1000,
    updateFunction: async (key:MyInterface) => {
        let result = await makeSomeRequestAsync(key)
        // ..
        return result
    }
})

setUpdateFunction(updateFunctionAsync:(key:K)=>Promise<V>|V)

Change the update function.

    myCachedMap.setUpdateFunction((key:K) => key+'!')

async getAsync(key:K):Promise<V>

Get value by key.

    const result = await myCachedMap.getAsync()

clearCache()

Clear cache and force to update all values.

    myCachedMap.clearCache()

clearCacheForKey(key:K)

Force to update value only for specified key.

    myCahcedMap.clearCacheForKey('myKey')

BoxedValue<T>

BoxedValue is a wrapper for any value. Value can be undefined.

Example

    let x = new BoxedValue<number|undefined>()
    x.hasValue // false

    x.set(undefined)
    x.hasValue // true
    x.getOrThrow() // undefined

    x.set(100)
    x.getOrThrow() // 100

constructor

    let myBoxedValue = new BoxedValue<T>(initialValue?:T)

Example

    let myBoxedValue = new BoxedValue<number>(100)

get hasValue():boolean

Check if box has a value.

    myBoxedValue.hasValue // true or false

get isEmpty():boolean

Check if box is empty.

    myBoxedValue.isEmpty // true or false

set(value:T)

Set new value.

    myBoxedValue.set(100)

setByPrevious(action:(previousValue?:T)=>T)

Set new value by using previous value.

    myBoxedValue.setByPrevious((prev:number) => prev+1)

getOrThrow()

Return value if exists else throw an error.

    try {
        let currentValue = myBoxedValue.getOrThrow()
        console.log('value exists, currentValue=', currentValue)

    } catch(x){
        console.error('no value', x)

    }

getOrUndefined():T|undefined

Return value if exists else return undefined.

    const myBoxedValue = new BoxedValue<number>()
    myBoxedValue.getOrUndefined() // undefined
    myBoxedValue.set(100)
    myBoxedValue.getOrUndefined() // 100

deleteValue()

Delete value if exists.

    myBoxedValue.set(100)
    myBoxedValue.getOrUndefined() // 100
    myBoxedValue.deleteValue()
    myBoxedValue.hasValue //false
    myBoxedValue.getOrUndefined() // undefined

get lastModifactionDate()

Returns last modification date.

If no value has been set yet then retuns date when instance was created.

    console.log('last modification date = ', myBoxedValue.lastModificationDate)