Skip to content
This repository was archived by the owner on Oct 1, 2021. It is now read-only.

Repository files navigation

Services-Cache

semantic-release

Build Status

Services-cache is a Redis cache plugin for LabShare Services.

Requirements

Development

npm i @labshare/services-cache

*You might need to use sudo (UNIX).

labshare/services-cache

Simple and extensible caching module with redis and memory storage and supporting decorators.

Install

 npm install --save @labshare/services-cache 

Usage

Steps to use directly in Simple Express Application

Step: 1

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
}
}
}
```

Step: 2

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});}}}

Steps to use in Simple Loopback Application

Step 1 : Bind the ServicesCache component to application

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 ...}}
...
...

Step 2 : With decorator

With decorator

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"];}}

Directly in the code with loopback application.

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;}}

Types

LabShareCache

Cached items expire after a given amount of time.

  • ttl: (Default: 60) Number of seconds to expire the cachte item
  • isLazy: (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?: string
  • refreshCache: boolean.

Storages

StorageConfiguration
RedisRedisStorage({redis}:RedisClientOptions)
memoryMemoryStorage({memory}: isGlobalCache =true creates a global instance for local memory, if false is a local storage per instance)

Test

 npm test

Note

The cache's duration is in seconds, also maxTime is used if no duration is given.

License

MIT

About

Cache plugin for LabShare Services

Topics

Resources

Stars

1 star

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages