Skip to content

Commit

Permalink
add cache parameter to enable cache and disable cache by defeault
Browse files Browse the repository at this point in the history
  • Loading branch information
CahidArda committed Apr 17, 2024
1 parent 57f5263 commit e36c180
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions src/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,14 @@ export type AnalyticsConfig = {
* Buckets are evicted when they are read, not when they are written. This is much cheaper since
* it only requires a single command to ingest data.
*/
retention?: Window | number;
retention?: Window | number

/**
* Whether to initialize a cache. Cache is used in the `loadBuckets` method, which in turn is
* called in `count`, `aggregateBy` and `query` methods. This means that to only use `ingest`,
* there is no need to use cache.
*/
cache?: boolean
};

class Cache<TValue> {
Expand Down Expand Up @@ -86,13 +93,14 @@ export class Analytics {
private readonly bucketSize: number;
private readonly retention?: number;

private readonly cache = new Cache<Record<string, number>>(60000);
private readonly cache?: Cache<Record<string, number>>;

constructor(config: AnalyticsConfig) {
this.redis = config.redis;
this.prefix = config.prefix ?? "@upstash/analytics";
this.bucketSize = this.parseWindow(config.window);
this.retention = config.retention ? this.parseWindow(config.retention) : undefined;
this.cache = config.cache ? new Cache(60000) : undefined;
}

private validateTableName(table: string) {
Expand Down Expand Up @@ -206,14 +214,16 @@ export class Analytics {
const loadKeys: string[] = [];
const buckets: { key: string; hash: Record<string, number> }[] = [];
for (const key of keys) {
const cached = this.cache.get(key);
if (cached) {
buckets.push({
key,
hash: cached,
});
} else {
loadKeys.push(key);
if (this.cache) {
const cached = this.cache.get(key);
if (cached) {
buckets.push({
key,
hash: cached,
});
} else {
loadKeys.push(key);
}
}
}

Expand All @@ -225,7 +235,7 @@ export class Analytics {
for (let i = 0; i < loadKeys.length; i++) {
const key = loadKeys[i];
const hash = res[i];
if (hash) {
if (hash && this.cache) {
this.cache.set(key, hash);
}
buckets.push({
Expand Down

0 comments on commit e36c180

Please sign in to comment.