0.2.0 • Published 3 years ago

dynamodb-as-cache v0.2.0

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

DynamoDB as Cache

Use DynamoDB as cache service, providing Redis-like APIs and reducing the boilerplate of dealing low-level DynamoDB APIs.

Why

DynamoDB requires minimum maintenance overhead and acceptable performance in quite many cases. Often we just need a simple centralized key-value storage for our distributed services.

Where extreme performance is required, we can still easily migrate our code to use Redis.

Installation

npm i dynamodb-as-cache

Example

const { DCacheClient } = require('../index')
const { promisify } = require('util')

const sleep = promisify(setTimeout)

async function main() {
  try {
    const client = new DCacheClient({
      region: process.env.AWS_REGION,
      tableName: process.env.TABLE_NAME
    })

    await client.set('foo', { message: 'hello foo' }, 1)
    await client.set('bar', { message: 'hello bar' }, 10)
    await sleep(3000)
    const v1 = await client.get('foo')
    const v2 = await client.get('bar')

    v1? console.log('v1: cache hit =>', v1) : console.log('v1: cache miss')
    v2? console.log('v2: cache hit =>', v2) : console.log('v2: cache miss')

    const _v3 = await client.getset('foo', { message: 'hello foo again' }, 1)
    const _v4 = await client.getset('bar', { message: 'hello bar again' }, 10)
    const v3 = await client.get('foo')
    const v4 = await client.get('bar')
    console.log(`v3: old = ${_v3}  new= ${v3}`)    
    console.log(`v4: old = ${_v4}  new= ${v4}`)    

  } catch (e) {
    console.error('something went wrong', e)
  }
}

main().catch(console.error)

API

constructor(options)

Options

  • region - string, required. AWS region, e.g. us-east-1
  • tableName - string, required. DynamoDB table name
  • accessKeyId - string, optional. AWS Access Key Id
  • secretAccessKey - string, optional. AWS Secret Access Key
  • partionKey - string, optional. (default: pkey)
  • sortKey - string, optional. (default: skey)
  • ttlAttribute - string, optional. (default: ttl)
  • consistentRead - boolean, optional. (default: false)
  • defaultSortKeyValue - string, optional. (default: DCache)

set(pkey, value, ttl = null, options)

Returns Promise, which

  • resovled with empty object
  • rejected when dynamodb throws error

Arguments:

  • pkey partition key
  • value value to cache
  • ttl time to live (in seconds), default: null
  • options options, default: {}

getset(pkey, value, ttl = null, options)

Returns Promise, which

  • resovled with old cached value
  • rejected when dynamodb throws error

Arguments:

  • pkey partition key
  • value value to cache
  • ttl time to live (in seconds), default: null
  • options options, default: {}

get(pkey, options)

Returns Promise, which

  • resovled with cached value
  • rejected when dynamodb throws error

Arguments:

  • pkey partition key
  • options options, default: {}