Introduction to Catbox
Catbox is a versatile and efficient tool designed for handling various types of data storage and retrieval. Whether working with simple key-value pairs or more complex structures like distributed caching, Catbox provides a plethora of APIs to meet your needs. Below, we explore some of the most useful Catbox APIs with detailed code snippets and a complete app example.
Catbox API Examples
Below are dozens of Catbox API examples to help you get started:
Creating a Cache Client
const Catbox = require('@hapi/catbox'); const Client = new Catbox.Client(require('@hapi/catbox-memory')); await Client.start(); console.log('Cache client started');
Setting a Cache Item
const key = { id: 'example', segment: 'test' }; const value = { a: 1, b: 2 }; await Client.set(key, value, 10000); // Cache for 10 seconds console.log('Item set in cache');
Getting a Cache Item
const cached = await Client.get(key); if (cached) { console.log('Cache hit:', cached.item); } else { console.log('Cache miss'); }
Using Catbox Policies
const policy = new Catbox.Policy({ expiresIn: 30000 }, Client, 'exampleSegment'); await policy.set('exampleKey', { data: 'exampleData' }); const cachedPolicyItem = await policy.get('exampleKey'); console.log(cachedPolicyItem);
Deleting a Cache Item
await Client.drop(key); console.log('Item dropped from cache');
Complete App Example Using Catbox
Here is a complete example of a Node.js application using Catbox’s APIs:
const Catbox = require('@hapi/catbox'); const Hapi = require('@hapi/hapi'); const startServer = async () => { const server = Hapi.server({ port: 3000, host: 'localhost' }); const cacheClient = new Catbox.Client(require('@hapi/catbox-memory')); await cacheClient.start(); server.app.cache = cacheClient; server.route({ method: 'GET', path: '/cache', handler: async (request, h) => { const key = { id: 'simpleCache', segment: 'api' }; const cached = await request.server.app.cache.get(key); if (cached) { return cached.item; } const value = { message: 'Hello, World!' }; await request.server.app.cache.set(key, value, 30000); return value; } }); await server.start(); console.log('Server running on %s', server.info.uri); }; startServer().catch(err => { console.error('Server startup error:', err); });
This example demonstrates how to integrate Catbox caching into an HTTP server built with Hapi.js. The `/cache` endpoint will cache the response and serve it from the cache if available to improve performance.
Happy caching with Catbox!
Hash: f7a8850402f7a329ff666856e3a2ed0ef63c5081388e8fd405339adf1ef948aa