npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

adonis5-cache

v1.3.1

Published

Cache provider for AdonisJS 5

Downloads

2,243

Readme

Adonis5-Cache

In memory cache for Adonis JS, Redis cache for Adonis JS , AdonisJS, Cache for Adonis, Memcached storage

typescript-image npm-image license-image

Cache for AdonisJS 5

Supported cache storages:

  • Redis storage
  • In memory storage
  • Memcached storage

Table of contents

Installation

npm i --save adonis5-cache

Compile your code:

node ace serve --watch

Install provider:

node ace invoke adonis5-cache
  • For other configuration, please update the config/cache.ts.

Sample Usage

After adding cache provider to your app, you can import CacheManager for accessing to cache.

 import Cache from '@ioc:Adonis/Addons/Adonis5-Cache'
  • For example you can use cache for reduce amount of requests to external API. You can storing responses to cache in such way:
      
    import Cache from '@ioc:Adonis/Addons/Adonis5-Cache'
      
    export default class Service {
      constructor () {
      }
      
      public async loadDataFromExternalApi (userCode) {
        let userData = await Cache.get<UserDTO>(userCode)
        if (!userData) {
          userData = //load data from external api
          await Cache.put(userData)
        }    
     
        return userData
      }
    }

Custom storages

You can add additional cache storages for saving cache data. You have to implement CacheStorageContract interface by your class:

import { CacheStorageContract } from '@ioc:Adonis/Addons/Adonis5-Cache'

class CustomCacheStorage implements CacheStorageContract {

	get<T = any>(context: CacheContextContract, key: string): Promise<T | null> {
		// method implementation
	}

	getMany<T = any>(context: CacheContextContract, keys: string[]): Promise<(T | null)[]> {
		// method implementation
	}

	put(context: CacheContextContract, key: string, value, ttl: number): Promise<void> | void {
		// method implementation
	}

	putMany(context: CacheContextContract, cacheDictionary, ttl: number): Promise<void> | void {
		// method implementation
	}

}

After creating custom storage you have to register your storage to cache manager:

import Cache from '@ioc:Adonis/Addons/Adonis5-Cache'

Cache.registerStorage('storage-name', storageInstance)

Redis storage

For using redis storage install adonis-redis package

npm i @adonisjs/redis@alpha

After it you should invoke generator for configuring package:

node ace invoke @adonisjs/redis

Configure redis in config/redis.ts and add redis storage to cache config in config/cache.ts:

{
	"currentCacheStorage": "redis",
	"enabledCacheStorages": [
		"redis"
	]
}

Memcached storage

For using memcached storage install adonis-memcached client

npm i adonis5-memcached-client

After it you should invoke generator for configuring package:

node ace invoke adonis5-memcached-client

Configure memcached client in config/memcached.ts and add memcached storage to cache config in config/cache.ts:

{
	"currentCacheStorage": "memcached",
	"enabledCacheStorages": [
		"memcached"
	]
}

Storage toggle

After registration you can use your storage in such way:

const cachedValue = await Cache.viaStorage('storage-name').get('cache-key')

Or you can enable your storage as default cache storage:

Cache.enableStorage('storage-name')

const cachedValue = await Cache.get('cache-key') // value will be received from your storage

Custom context

Cache contexts responsible for serialization and deserialization your data to cache storages. For example you can add additional keys or transform you data before serialization and deserialization processes.

You can implement your context is like to custom cache storage, your custom context have to implement ** CacheContextContract**:

import { CacheContextContract } from '@ioc:Adonis/Addons/Adonis5-Cache'

const customContext: CacheContextContract = {
	
	serialize: (data: any) => { JSON.stringify({ data: data, serializedAt: Date.now })},
	
	deserialize: (cacheRecord:string) => ({ ...JSON.parse(cacheRecord), deserializedAt: Date.now }),
}

After implementation you have to register new context:

Cache.registerContext('custom-context-name', customContext)

And then you can using new context when you accessing to cache storage:

const cachedValue = await Cache.get<RecordDTO>('cache-key') // Reading data from cache using custom context

await Cache.put('cache-key', cachedData) // Storing data to cache using custom context

Enable custom context as default

Of course, you can enable your custom context as default cache context:


Cache.enableContext('custom-context-name') // After this your cache operations will be use your custom context

Cache fallback

You can pass fallback value when you calling get method:

const cachedValue = await Cache.get < RecordDTO > ('cache-key', fallbackValue)

Or pass async function as fallback value in the following way

const cachedValue = await Cache.get<RecordDTO>('cache-key', async () => { 
  return callApi(); 
})

If cache storage value doesn't exists fallback value will storage to cache by selected key. You can specify ttl for fallback value as function parameter:

const cachedValue = await Cache.get<RecordDTO>('cache-key', fallbackValue, customTTL)

Cache events

Cache provider implements several events:

  • cache-record:read
  • cache-record:written
  • cache-record:missed
  • cache-record:forgotten

You can add listener for this events in the following ways:

import Event from '@ioc:Adonis/Core/Event'

Event.on('cache-record:missed', 'CacheEventListener.handleCacheRecordMissedEvent')

You can configure which events are emitted with cache config:

{
	recordTTL: 10000,
	currentCacheStorage: 'redis',
	enabledCacheStorages: ['redis'],
	cacheKeyPrefix: '',
	enabledEvents: {
		'cache-record:read': false,
		'cache-record:written': false,
		'cache-record:missed': false,
		'cache-record:forgotten': false,
	}
}

Cache tags

When you need partial flushing your cache you can use cache tags. This features allow you tag your cache records and then flush only tagged records. For using cache tags you should call method tags on cache manager with list of your tags as argument, then you get TaggedCacheManager, which allow you using tagged cache functionality.

Cache.tags('tag-1', 'tag-2', 'tag-3')

Actually for writing cache record with tags you can in the following way:

await Cache.tags('tag-1', 'tag-2', 'tag-3').put('key', 'value')

Or store dictionary with cache records: Actually for writing cache record with tags you can in the following way:

await Cache.tags('tag-1', 'tag-2', 'tag-3').putMany({ key: 'value' })

Then you can clear tagged records in the following way:

await Cache.tags('tag-1', 'tag-2', 'tag-3').flush()

During this operation tags and tagger records will be removed from storage, however records with another tags will remain in your storage. This is great feature for storing responses from different API's. You can tag each response by appropriate tag and flush responses only for desirable API.

Cache record TTL

You can configure record TTL using cache config:

{	
    recordTTL: 60000,
    ttlUnits: 'ms'
}

Or you can set record ttl as function parameter:

 await Cache.put(userData, 1000)

Your value will be transformed to milliseconds using time units which configured by ttlUnits parameter in your cache config.