@cacher/cacher
Advanced tools
Comparing version
export * from './adapter'; | ||
export * from './memory'; | ||
export * from './union'; |
@@ -33,2 +33,53 @@ 'use strict'; | ||
class UnionAdapter { | ||
constructor({ adapters, repliceTtl, replicaMode = true }) { | ||
this.adapters = adapters; | ||
this.repliceTtl = repliceTtl; | ||
this.replicaMode = replicaMode; | ||
} | ||
async get(keys) { | ||
const [firstAdapter, secondAdapter] = this.adapters; | ||
const firstItems = await firstAdapter.get(keys); | ||
const keysForSecond = keys.filter((item, index) => (firstItems[index] === undefined)); | ||
if (keysForSecond.length === 0) { | ||
return firstItems; | ||
} | ||
const secondResult = await secondAdapter.get(keysForSecond); | ||
if (this.replicaMode) { | ||
const list = []; | ||
keysForSecond.forEach((key, index) => { | ||
const value = secondResult[index]; | ||
if (value === undefined) { | ||
return; | ||
} | ||
list.push({ | ||
key, | ||
value, | ||
ttl: this.repliceTtl | ||
}); | ||
}); | ||
if (list.length !== 0) { | ||
await firstAdapter.set(list); | ||
} | ||
} | ||
let index = 0; | ||
// eslint-disable-next-line no-return-assign | ||
return firstItems.map(item => (item !== undefined | ||
? item | ||
: secondResult[index += 1])); | ||
} | ||
async set(keys) { | ||
await Promise.all(this.adapters.map(adapter => (adapter.set(keys)))); | ||
} | ||
async delete(keys) { | ||
await Promise.all(this.adapters.map(adapter => (adapter.delete(keys)))); | ||
} | ||
async touch(keys) { | ||
await Promise.all(this.adapters.map(adapter => (adapter.touch(keys)))); | ||
} | ||
async clear(namespace) { | ||
await Promise.all(this.adapters.map(adapter => (adapter.clear(namespace)))); | ||
} | ||
} | ||
const arraify = (value) => (Array.isArray(value) | ||
@@ -86,1 +137,2 @@ ? value | ||
exports.MemoryAdapter = MemoryAdapter; | ||
exports.UnionAdapter = UnionAdapter; |
{ | ||
"name": "@cacher/cacher", | ||
"version": "0.0.1", | ||
"version": "0.1.0", | ||
"description": "Modern implementation of key-value storage", | ||
@@ -5,0 +5,0 @@ "license": "MIT", |
10878
32.11%11
10%225
44.23%