forked from havsar/node-ts-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(multicache): allow caching multiple keys at once
- Loading branch information
Showing
8 changed files
with
274 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
import { MultiAsynchronousCacheType, MultiSynchronousCacheType } from ".."; | ||
|
||
const defaultKeyStrategy = { | ||
getKey( | ||
className: string, | ||
methodName: string, | ||
parameter: any, | ||
args: any | ||
): string { | ||
return `${className}:${methodName}:${JSON.stringify( | ||
parameter | ||
)}:${JSON.stringify(args)}`; | ||
}, | ||
}; | ||
|
||
export function MultiCache( | ||
cachingStrategies: (MultiAsynchronousCacheType | MultiSynchronousCacheType)[], | ||
parameterIndex = 0, | ||
keyStrategy = defaultKeyStrategy | ||
): Function { | ||
return function ( | ||
target: Object /* & { | ||
__cache_decarator_pending_results: { | ||
[key: string]: Promise<any> | undefined; | ||
}; | ||
}*/, | ||
methodName: string, | ||
descriptor: PropertyDescriptor | ||
) { | ||
const originalMethod = descriptor.value; | ||
const className = target.constructor.name; | ||
|
||
descriptor.value = async function (...args: any[]) { | ||
const runMethod = async (newSet: any[]) => { | ||
const newArgs = [...args]; | ||
newArgs[parameterIndex] = newSet; | ||
|
||
const methodCall = originalMethod.apply(this, newArgs); | ||
|
||
let methodResult; | ||
|
||
const isAsync = | ||
methodCall?.constructor?.name === "AsyncFunction" || | ||
methodCall?.constructor?.name === "Promise"; | ||
if (isAsync) { | ||
methodResult = await methodCall; | ||
} else { | ||
methodResult = methodCall; | ||
} | ||
return methodResult; | ||
}; | ||
|
||
const parameters = args[parameterIndex]; | ||
const cacheKeys: (string| undefined)[] = parameters.map((parameter: any) => { | ||
return keyStrategy.getKey(className, methodName, parameter, args); | ||
}); | ||
|
||
let result: any[] = []; | ||
if (!process.env.DISABLE_CACHE_DECORATOR) { | ||
let currentCachingStrategy = 0; | ||
do { | ||
// console.log('cacheKeys', cacheKeys, currentCachingStrategy) | ||
const foundEntries = ((await cachingStrategies[ | ||
currentCachingStrategy | ||
]) as any).getItems(cacheKeys.filter(key => key !== undefined)); | ||
|
||
// console.log('foundEntries', foundEntries); | ||
|
||
// remove all foudn entries from cacheKeys | ||
Object.keys(foundEntries).forEach((entry) => { | ||
if (foundEntries[entry] === undefined) return; | ||
// remove entry from cacheKey | ||
cacheKeys[cacheKeys.indexOf(entry)] = undefined; | ||
}); | ||
// save back to strategies before this strategy | ||
if (currentCachingStrategy > 0) { | ||
const setCache = | ||
Object.keys(foundEntries).map((key) => ({ | ||
key, | ||
content: foundEntries[key], | ||
})).filter(f => f.content !== undefined); | ||
|
||
if (setCache.length > 0) { | ||
let saveCurrentCachingStrategy = currentCachingStrategy - 1; | ||
do { | ||
await cachingStrategies[saveCurrentCachingStrategy].setItems(setCache); | ||
|
||
saveCurrentCachingStrategy--; | ||
} while (saveCurrentCachingStrategy >= 0); | ||
} | ||
} | ||
|
||
// save to final result | ||
|
||
result = [...result, ...Object.values(foundEntries).filter(f => f !== undefined)]; | ||
// console.log('result', result); | ||
|
||
currentCachingStrategy++; | ||
} while ( | ||
cacheKeys.filter(key => key !== undefined).length > 0 && | ||
currentCachingStrategy < cachingStrategies.length | ||
); | ||
} | ||
|
||
if (cacheKeys.filter(key => key !== undefined).length > 0) { | ||
// use original method to resolve them | ||
const missingKeys = cacheKeys.map((key, i) => { | ||
if (key !== undefined) { | ||
return parameters[i] | ||
} | ||
return undefined; | ||
}).filter(k => k !== undefined); | ||
|
||
const originalMethodResult: any[] = await runMethod(missingKeys); | ||
if (originalMethodResult.length !== missingKeys.length) { | ||
throw new Error( | ||
"input and output has different size! input: " + | ||
cacheKeys.length + | ||
", returned " + | ||
originalMethodResult.length | ||
); | ||
} | ||
|
||
// console.log('originalMethodResult', originalMethodResult); | ||
if (!process.env.DISABLE_CACHE_DECORATOR) { | ||
// save back to all caching strategies | ||
const saveToCache = | ||
originalMethodResult.map((content, i) => { | ||
return { | ||
key: keyStrategy.getKey(className, methodName, missingKeys[i], args), | ||
content, | ||
} | ||
}); | ||
|
||
// console.log('saveToCache', saveToCache); | ||
|
||
let saveCurrentCachingStrategy = cachingStrategies.length - 1; | ||
do { | ||
await cachingStrategies[saveCurrentCachingStrategy].setItems(saveToCache); | ||
|
||
saveCurrentCachingStrategy--; | ||
} while (saveCurrentCachingStrategy >= 0); | ||
} | ||
|
||
result = [...result, ...originalMethodResult]; | ||
} | ||
|
||
return result; | ||
}; | ||
|
||
return descriptor; | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
//import * as Assert from "assert"; | ||
import {MultiCache} from "../src/decorator/multicache.decorator"; | ||
import {LRUStorage} from "../../storages/lru/src/LRUStorage"; | ||
import {NodeCacheStorage} from "../../storages/node-cache/src/node-cache.storage"; | ||
|
||
const storage = new LRUStorage({}); | ||
const storage2 = new NodeCacheStorage({}); | ||
|
||
// const data = ["user", "max", "test"]; | ||
|
||
storage2.setItem('TestClassOne:cachedCall:"elem3":[["elem1","elem2","elem3"]]', 'STORAGE2'); | ||
storage.setItem('TestClassOne:cachedCall:"elem2":[["elem1","elem2","elem3"]]', 'STORAGE1'); | ||
|
||
class TestClassOne { | ||
callCount = 0; | ||
|
||
@MultiCache([storage, storage2], 0/*, { | ||
getKey(className: string, methodName: string, parameter: any, args: any): string { | ||
return 'canonical:' + parameter + | ||
} | ||
}*/) | ||
public cachedCall(param0: string[]): string[] { | ||
console.log('called with', param0); | ||
return param0.map(p => p + 'RETURN VALUE'); | ||
} | ||
} | ||
|
||
describe("MultiCacheDecorator", () => { | ||
beforeEach(async () => { | ||
// await storage.clear(); | ||
// await storage2.clear(); | ||
}); | ||
|
||
it("Should multi cache", async () => { | ||
const myClass = new TestClassOne(); | ||
// call 1 | ||
const call1= await myClass.cachedCall(['elem1', 'elem2', 'elem3']); | ||
console.log('CALL1', call1); | ||
|
||
const call2= await myClass.cachedCall(['elem1', 'elem2', 'elem3']); | ||
console.log('CALL2', call2); | ||
}); | ||
}); |