58 lines
1.4 KiB
TypeScript
58 lines
1.4 KiB
TypeScript
import * as plugins from '../plugins.ts';
|
|
|
|
/** TTL duration constants in milliseconds */
|
|
export const TTL = {
|
|
MINUTES_5: 5 * 60 * 1000,
|
|
HOURS_1: 60 * 60 * 1000,
|
|
HOURS_24: 24 * 60 * 60 * 1000,
|
|
DAYS_7: 7 * 24 * 60 * 60 * 1000,
|
|
DAYS_30: 30 * 24 * 60 * 60 * 1000,
|
|
DAYS_90: 90 * 24 * 60 * 60 * 1000,
|
|
} as const;
|
|
|
|
/**
|
|
* Abstract base class for cached documents with TTL support.
|
|
* Extend this class and add @Collection decorator pointing to your CacheDb.
|
|
*/
|
|
export abstract class CachedDocument<
|
|
T extends CachedDocument<T>,
|
|
> extends plugins.smartdata.SmartDataDbDoc<T, T> {
|
|
@plugins.smartdata.svDb()
|
|
public createdAt: number = Date.now();
|
|
|
|
@plugins.smartdata.svDb()
|
|
public expiresAt: number = Date.now() + TTL.HOURS_1;
|
|
|
|
@plugins.smartdata.svDb()
|
|
public lastAccessedAt: number = Date.now();
|
|
|
|
constructor() {
|
|
super();
|
|
}
|
|
|
|
/** Set TTL in milliseconds from now */
|
|
setTTL(ms: number): void {
|
|
this.expiresAt = Date.now() + ms;
|
|
}
|
|
|
|
/** Set TTL in days from now */
|
|
setTTLDays(days: number): void {
|
|
this.setTTL(days * 24 * 60 * 60 * 1000);
|
|
}
|
|
|
|
/** Set TTL in hours from now */
|
|
setTTLHours(hours: number): void {
|
|
this.setTTL(hours * 60 * 60 * 1000);
|
|
}
|
|
|
|
/** Check if this document has expired */
|
|
isExpired(): boolean {
|
|
return Date.now() > this.expiresAt;
|
|
}
|
|
|
|
/** Update last accessed timestamp */
|
|
touch(): void {
|
|
this.lastAccessedAt = Date.now();
|
|
}
|
|
}
|