UNPKG

andresusandi-storage

Version:

storage utilities for distributed systems

54 lines (43 loc) 1.54 kB
const { name: packageName } = require('./package.json'); const PREFIX = "key-gen-"; class ConsistentHashShard { constructor(shardIndex, storageConstructor, counterConstructor) { this.shardIndex = shardIndex; this.name = PREFIX + shardIndex.toString(); this.storageConstructor = storageConstructor; this.storage = null; this.counterConstructor = counterConstructor; this.counter = null; } async init() { this.storage = this.storageConstructor(this.shardIndex); await this.storage.init(); this.counter = this.counterConstructor(); const itemCount = (await this.storage.getAllItems()).length; await this.counter.set(this.name, itemCount); console.log(`${packageName}/${this.constructor.name}: Initialized instance of shard for ${this.shardIndex} with ${itemCount} items`); } async save(key, value) { await this.storage.save(key, value); } async get(key) { return(await this.storage.get(key)); } async delete(key) { await this.storage.delete(key); } async getAllItems() { return (await this.storage.getAllItems()); } async getCount() { const result = await this.counter.get(this.name); return (result.value); } async setCount(itemCount) { await this.counter.set(this.name, itemCount); } async modifyCount(byCount) { await this.counter.add(this.name, byCount); } } module.exports = ConsistentHashShard;