const redis = require('redis');
// Inventory Management System using ChronDB via Redis protocol
class InventorySystem {
constructor() {
this.client = redis.createClient({
url: 'redis://localhost:6379'
});
this.client.on('error', err => console.error('Redis Client Error:', err));
}
async connect() {
await this.client.connect();
console.log('Connected to ChronDB');
return this;
}
async disconnect() {
await this.client.quit();
console.log('Disconnected from ChronDB');
}
// Product management
async addProduct(id, details) {
const productKey = `product:${id}`;
const productData = {
...details,
createdAt: new Date().toISOString(),
lastModified: new Date().toISOString()
};
await this.client.set(productKey, JSON.stringify(productData));
return productData;
}
async getProduct(id) {
const productKey = `product:${id}`;
const data = await this.client.get(productKey);
return data ? JSON.parse(data) : null;
}
async updateProduct(id, updates) {
const productKey = `product:${id}`;
const currentData = await this.getProduct(id);
if (!currentData) {
throw new Error(`Product ${id} not found`);
}
const updatedData = {
...currentData,
...updates,
lastModified: new Date().toISOString()
};
await this.client.set(productKey, JSON.stringify(updatedData));
return updatedData;
}
async deleteProduct(id) {
const productKey = `product:${id}`;
return await this.client.del(productKey);
}
// Inventory operations
async adjustStock(id, adjustment) {
const product = await this.getProduct(id);
if (!product) {
throw new Error(`Product ${id} not found`);
}
const currentStock = product.stock || 0;
const newStock = currentStock + adjustment;
if (newStock < 0) {
throw new Error(`Insufficient stock for product ${id}`);
}
return this.updateProduct(id, { stock: newStock });
}
// Version control features
async getProductHistory(id) {
const productKey = `product:${id}`;
return await this.client.sendCommand(['CHRONDB.HISTORY', productKey]);
}
async getProductAtTime(id, timestamp) {
const productKey = `product:${id}`;
const data = await this.client.sendCommand(['CHRONDB.GETAT', productKey, timestamp]);
return data ? JSON.parse(data) : null;
}
// Searching inventory
async findProducts(pattern) {
const keys = await this.client.keys(pattern);
if (keys.length === 0) return [];
const productsData = await this.client.mGet(keys);
return productsData.map(data => JSON.parse(data));
}
// Bulk operations with transactions
async bulkUpdateStock(updates) {
const multi = this.client.multi();
for (const [id, adjustment] of Object.entries(updates)) {
const productKey = `product:${id}`;
const productData = await this.client.get(productKey);
if (!productData) {
throw new Error(`Product ${id} not found`);
}
const product = JSON.parse(productData);
const currentStock = product.stock || 0;
const newStock = currentStock + adjustment;
if (newStock < 0) {
throw new Error(`Insufficient stock for product ${id}`);
}
product.stock = newStock;
product.lastModified = new Date().toISOString();
multi.set(productKey, JSON.stringify(product));
}
return await multi.exec();
}
}
// Usage example
async function runInventoryExample() {
const inventory = await new InventorySystem().connect();
try {
// Add products
await inventory.addProduct('1001', {
name: 'Ergonomic Chair',
category: 'Furniture',
price: 299.99,
stock: 20
});
await inventory.addProduct('1002', {
name: 'Standing Desk',
category: 'Furniture',
price: 499.99,
stock: 15
});
await inventory.addProduct('2001', {
name: 'Wireless Keyboard',
category: 'Electronics',
price: 79.99,
stock: 50
});
// Get a product
const chair = await inventory.getProduct('1001');
console.log('Product details:', chair);
// Update a product
await inventory.updateProduct('1001', { price: 279.99, featured: true });
console.log('Product updated');
// Record sales (reduce stock)
await inventory.adjustStock('1001', -5);
await inventory.adjustStock('2001', -10);
console.log('Stock adjusted after sales');
// Get product history
const history = await inventory.getProductHistory('1001');
console.log('Chair price history:', history);
// Find all furniture products
const furniture = await inventory.findProducts('product:*');
const furnitureItems = furniture.filter(item => item.category === 'Furniture');
console.log('Furniture products:', furnitureItems);
// Bulk restock
await inventory.bulkUpdateStock({
'1001': 10,
'1002': 5,
'2001': 25
});
console.log('Bulk restock completed');
// Check current stock levels
const currentStock = await Promise.all([
inventory.getProduct('1001'),
inventory.getProduct('1002'),
inventory.getProduct('2001')
]);
console.log('Current stock levels:', currentStock.map(p => ({ id: p.id, name: p.name, stock: p.stock })));
} catch (err) {
console.error('Inventory system error:', err);
} finally {
await inventory.disconnect();
}
}
// Run the example
runInventoryExample();