Nucleus Powered Mitochondria

    fastify-cacheman

    1.0.0 • Public • Published

    fastify-cacheman

    NPM js-standard-style

    License NPM download/month NPM download total

    Small and efficient cache provider for Fastify with In-memory, File and Redis.

    Install using NPM

    $ npm install fastify-cacheman

    Usage

    const fastify = require('fastify')()
    const redis = require('redis')
    
    fastify.register(require('fastify-cacheman'), {
        engine: 'redis',
        client: redis.createClient('redis://localhost:6379')
    })
    
    fastify.get('/', async (req, reply) => {
      await fastify.cacheman.set('tester', 'world', 120) // this will cached for 120 seconds
    
      reply.send({ hello: await fastify.cacheman.get('tester') })
    })

    API

    options

    // using memory
    var options = {
      engine: 'memory'
    }
    
    // using file
    var options = {
      engine: 'file'
    }
    
    // using redis
    var options = {
      port: 6379,
      host: '127.0.0.1',
      password: 'my-p@ssw0rd'
      database: 1
    };
    
    // or using redis connection string
    var options = {
      engine: 'redis',
      client: redis.createClient('redis://localhost:6379')
    }

    cacheman.set(key, value, [ttl, [fn]])

    Stores or updates a value.

    fastify.cacheman.set('foo', { a: 'bar' }, function (err, value) {
      if (err) throw err;
      console.log(value); //-> {a:'bar'}
    });

    Or add a TTL(Time To Live) in seconds like this:

    // key will expire in 60 seconds
    fastify.cacheman.set('foo', { a: 'bar' }, 60, function (err, value) {
      if (err) throw err;
      console.log(value); //-> {a:'bar'}
    });

    cacheman.get(key, fn)

    Retrieves a value for a given key, if there is no value for the given key a null value will be returned.

    fastify.cacheman.get(function (err, value) {
      if (err) throw err;
      console.log(value);
    });

    cacheman.del(key, [fn])

    Deletes a key out of the cache.

    fastify.cacheman.del('foo', function (err) {
      if (err) throw err;
      // foo was deleted
    });

    cacheman.clear([fn])

    Clear the cache entirely, throwing away all values.

    fastify.cacheman.clear(function (err) {
      if (err) throw err;
      // cache is now clear
    });

    Note:

    • Support using callback, promise and async await style.
    • Redis 4 currently not supported.

    There are more spesific API for each engine type, please see:

    Unit test

    npm test

    When you run a test in your local PC, you will see an error in redis connection, because it was design to test in gitlab CI. So you have to edit the redis://redis:6379 become redis://127.0.0.1:6379.

    Install

    npm i fastify-cacheman

    DownloadsWeekly Downloads

    19

    Version

    1.0.0

    License

    MIT

    Unpacked Size

    8.15 kB

    Total Files

    8

    Last publish

    Collaborators

    • aalfiann