Caching Code Example

Suppose a client or middleware wishes to read data. They will first try to read a key-value-pair (KVP) from Bluzelle's cache. If the KVP is not yet in Bluzelle's cache, that is a "miss", and the client/middleware will fall back to requesting this data from the database directly. The database here is considered the "origin". This usage pattern of Bluzelle+DB is called cache-aside.

We will show you how to implement the cache-aside pattern in JavaScript.

For more information, please refer to Bluzelle's JavaScript API.

Setup

Begin by initializing the Bluzelle client in your code:

const bz = bluzelle({
entry: 'ws://testnet.bluzelle.com:51010',
uuid: '5f493479–2447–47g6–1c36-efa5d251a283',
private_pem: 'MHQCAQEEIFNmJHEiGpgITlRwao/CDki4OS7BYeI7nyz+CM8NW3xToAcGBSuBBAAKoUQDQgAEndHOcS6bE1P9xjS/U+SM2a1GbQpPuH9sWNWtNYxZr0JcF+sCS2zsD+xlCcbrRXDZtfeDmgD9tHdWhcZKIy8ejQ=='
});

The Read Pattern

We wish to read a record from the Bluzelle cache and fall back to our existing database.

try {
return await bz.read(key);
}
catch(e)
{
const value = await db.get(key);
await bz.update(key, value);
return value;
}

The Write Pattern

When writing records, write both to the cache and to the database.

await db.put(key, value)
await bz.update(key, value)