Services-cache is a Redis cache plugin for LabShare Services.
- Node.js v6+
- Redis (if Redis is not installed locally you can use this docker file)
npm i @labshare/services-cache*You might need to use sudo (UNIX).
Simple and extensible caching module with redis and memory storage and supporting decorators.
npm install --save @labshare/services-cache Create a Config folder in the root and add config file under config/default.json
```json
"services":
{
"cache": {
"type": "redis", // specifies if memory ( default) or redis storage is being selected.
"redis": {
"host": "ec2-52-90-18-4.compute-2.amazonaws.com", // eg : redis server "port": 6379
},
"memory":{
"isGlobalCache" : true
}
}
}
```
import{LabShareCache}from"@labshare/services-cache";constconfig=require('config');
...
...
// if redis constmyRedisCache=newLabShareCache(config.get('services.cache'));// if memory // change type to memoryconstmemoryCache=newLabShareCache(config.get('services.cache'));classMyService{/** * GET one hero by id */publicasyncgetOne(req: Request,res: Response,next: NextFunction){letquery=parseInt(req.params.id);constcachekey="cacheKey:"+query;constcachedSearchResults=awaitmyRedisCache.getItem<string>(cachekey);if(cachedSearchResults){returncachedSearchResults;}lethero=Heroes.find(hero=>hero.id===query);awaitmyRedisCache.setItem(cachekey,hero,{ttl: 120,isCachedForever: false});if(hero){res.status(200).send({message: 'Successfully',status: res.status,
hero
});}else{res.status(404).send({message: 'No hero found with the given id.',status: res.status});}}}import{ServicesCache}from'@labshare/services-cache';import{ServicesConfigComponent}from'@labshare/services-config';// Other imports …exportclassLbServicesExampleApplication{constructor(options: ApplicationConfig={}){// bindingthis.bind(CacheBindings.CACHE_CONFIG).to({"type": "redis","redis": {"host": "redis",// eg : redis server ec2-52-90-18-4.compute-1.amazonaws.com"port": 6379}});this.component(ServicesCache);// Method implementation ...}}
...
...Caches function response using the given options. Works with different strategies and storages. Uses all arguments to build an unique key.
@Cache(options)
options: Options passed to the cache provider for this particular method
Note: @Cache always converts the method response to a promise because caching might be async.
import{Cache}from"@labshare/services-cache";classMyService{
@Cache({ttl: 60})publicasyncgetUsers(): Promise<string[]>{return["John","Doe"];}}import{LabShareCache}from"@labshare/services-cache";classMyService{constructor(
@inject(CacheBindings.CACHE)privatecache: LabShareCache,){}publicasyncgetShipToUsers(): Promise<string[]>{constcachedUsers=awaitcache.getItem<string[]>("users");if(cachedUsers){returncachedUsers;}constnewUsers=["John","Doe"];awaitcache.setItem("users",newUsers,{ttl: 60});returnnewUsers;}}Cached items expire after a given amount of time.
ttl: (Default: 60) Number of seconds to expire the cachte itemisLazy: (Default: true) If true, expired cache entries will be deleted on touch. If false, entries will be deleted after the given ttl.noop?: boolean; // Allows for consuming libraries to conditionally disable caching. Set this to true to disable caching for some reason.cacheKey?: stringrefreshCache: boolean.
| Storage | Configuration |
|---|---|
| Redis | RedisStorage({redis}:RedisClientOptions) |
| memory | MemoryStorage({memory}: isGlobalCache =true creates a global instance for local memory, if false is a local storage per instance) |
npm testThe cache's duration is in seconds, also maxTime is used if no duration is given.
MIT