Created
January 15, 2020 17:03
-
-
Save davidecavaliere/15a6df76651e3e6a88d4115591a3fa6a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
export interface CacheOptions { | |
ttl: number; | |
} | |
export function Cache(options: CacheOptions) { | |
return (target: any, propertyKey: string, descriptor) => { | |
const originalFunction = descriptor.value; | |
target[`${propertyKey}_cached`] = new ReplaySubject(1, options.ttl); | |
descriptor.value = function(…args) { | |
const req = originalFunction.apply(this, args).pipe( | |
tap((response) => { | |
this[`${propertyKey}_cached`].next(response); | |
}) | |
); | |
return race(this[`${propertyKey}_cached`], req); | |
}; | |
return descriptor; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment