gearworks-cache
A simple in-memory cache used by Gearworks-based Shopify apps, backed by catbox and catbox-memory. Gearworks is the best way to get started with building Shopify applications!
Installing
You can install this package from NPM with the NPM CLI or with Yarn (recommended):
npm install gearworks-cache --save
yarn add gearworks-cache
Importing
You can import the cache helpers either one function at a time, or all at once, via require or TypeScript's import:
import * as Cache from "gearworks-cache";
import { setCacheValue } from "gearworks-cache";
const Cache = require("gearworks-cache");
const setCacheValue = require("gearworks-cache").setCacheValue;
Async and Promises
All functions in gearworks-cache
return Bluebird promises. If you're using TypeScript or transpiling your JS via Babel, you can use await
to wait for the promise to run.
await cache.initialize();
cache.initialize().then(() => {
})
Usage
initialize(): Promise
The cache must be initialized at application startup (or at least before you attempt to use any other function).
await Cache.initialize();
setValue(segmentName: string, key: string, value: , ttl: number = 3600000): Promise
Async function that saves the given value to the cache.
segmentName
: Name of the segment that the value will reside in, e.g. "auth-invalidation" or "recent-orders".
key
: Key/name of the value being set.
value
: Value to set in the cache. Must be json-serializable.
ttl
: (optional) Length of time that the value will reside in the cache, in milliseconds. Defaults to 60 minutes.
const key = "key_that_can_be_used_to_lookup_value";
const value = {
foo: "bar"
}
const time = 60 * 60 * 1000 * 24;
await Cache.setValue("foo-segment", key, value, time);
getValue(segmentName: string, key: string): Promise<CachedItem>
Async function that gets a value from the cache. Will return undefined if the value is not found.
segmentName
: Name of the segment that the value resides in, e.g. "auth-invalidation" or "recent-orders".
key
: Key/name of the value being retrieved.
const key = "key_that_can_be_used_to_lookup_value";
const cachedItem = await Cache.getValue<{foo: string}>("foo-segment", key);
const value = cachedItem.item;
Returns a CachedItem<T>
with the following interface:
interface CachedItem<T> {
item: T;
stored: number;
ttl: number;
}
deleteValue(segmentName: string, key: string): Promise
Async function that deletes a value from the cache.
segmentName
: Name of the segment that the value resides in, e.g. "auth-invalidation" or "recent-orders".
key
: Key/name of the value being deleted.
const key = "key_that_can_be_used_to_lookup_value";
await Cache.deleteValue("foo-segment", key);