Skip to content

Instantly share code, notes, and snippets.

@davidecavaliere
Created January 15, 2020 17:03
Show Gist options
  • Save davidecavaliere/15a6df76651e3e6a88d4115591a3fa6a to your computer and use it in GitHub Desktop.
Save davidecavaliere/15a6df76651e3e6a88d4115591a3fa6a to your computer and use it in GitHub Desktop.
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