slonik-interceptor-query-cache

Caches Slonik queries.

Usage no npm install needed!

<script type="module">
  import slonikInterceptorQueryCache from 'https://cdn.skypack.dev/slonik-interceptor-query-cache';
</script>

README

slonik-interceptor-query-cache

Travis build status Coveralls NPM version Canonical Code Style Twitter Follow

Caches Slonik queries.

Usage

Query cache interceptor is initialised using a custom storage service. The Example Usage documentation shows how to create a compatible storage service using node-cache.

Which queries are cached is controlled using cache attributes. Cache attributes are comments starting with @cache- prefix. Only queries with cache attributes are cached (see Cache attributes)

API

import {
  createQueryCacheInterceptor
} from 'slonik-interceptor-query-cache';

type CacheAttributesType = {|
  +ttl: number,
|};

type StorageType = {|
  +get: (query: QueryType, cacheAttributes: CacheAttributesType) => Promise<QueryResultType<QueryResultRowType> | null>,
  +set: (query: QueryType, cacheAttributes: CacheAttributesType, queryResult: QueryResultType<QueryResultRowType>) => Promise<void>,
|};

type ConfigurationInputType = {|
  +storage: StorageType,
|};

type ConfigurationType = {|
  +storage: StorageType,
|};

(configurationInput: ConfigurationInputType) => InterceptorType;

Cache attributes

Cache attribute Description Required? Default
@cache-ttl Number (in seconds) to cache the query for. Yes N/A

Example usage

This example shows how to create a compatible storage service using node-cache.

import NodeCache from 'node-cache';
import {
  createPool
} from 'slonik';
import {
  createQueryCacheInterceptor
} from 'slonik-interceptor-query-cache';

const nodeCache = new NodeCache({
  checkperiod: 60,
  stdTTL: 60,
  useClones: false,
});

const hashQuery = (query: QueryType): string => {
  return JSON.stringify(query);
};

const interceptors = [
  createQueryCacheInterceptor({
    storage: {
      get: (query) => {
        return cache.get(hashQuery(query)) || null;
      },
      set: (query, cacheAttributes, queryResult) => {
        cache.set(hashQuery(query), queryResult, cacheAttributes.ttl);
      },
    },
  }),
];

const pool = createPool('postgres://', {
  interceptors
});

await connection.any(sql`
  -- @cache-ttl 60
  SELECT
    id,
    code_alpha_2
  FROM country
  WHERE
    code_alpha_2 = ${countryCode}
`);