Skip to content

Commit

Permalink
feat(cache): cacheTTL
Browse files Browse the repository at this point in the history
  • Loading branch information
jiawei397 committed Jan 18, 2022
1 parent f32c116 commit 5132b8c
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
20 changes: 18 additions & 2 deletions modules/cache/example/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { Controller, Get, Query, UseInterceptors } from "../../../mod.ts";
import { CacheInterceptor } from "../mod.ts";
import {
Controller,
Get,
Params,
Query,
UseInterceptors,
} from "../../../mod.ts";
import { CacheInterceptor, CacheTTL } from "../mod.ts";

@Controller("")
@UseInterceptors(CacheInterceptor)
Expand All @@ -14,4 +20,14 @@ export class AppController {
}, 500);
});
}

@Get("/delay/:id")
@CacheTTL(3000)
delay2(@Params("id") id: string) {
return new Promise((resolve) => {
setTimeout(() => {
resolve("delay " + id);
}, 500);
});
}
}
2 changes: 2 additions & 0 deletions modules/cache/src/cache.constant.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export const optionKey = Symbol("options");

export const META_CACHE_TTL_KEY = Symbol("meta:cache:ttl");
16 changes: 14 additions & 2 deletions modules/cache/src/cache.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,18 @@ import {
NestInterceptor,
NestInterceptorOptions,
Next,
Reflect,
} from "../../../mod.ts";
import { isDebug } from "../../../src/utils.ts";
import { optionKey } from "./cache.constant.ts";
import { META_CACHE_TTL_KEY, optionKey } from "./cache.constant.ts";
import { CacheModuleOptions } from "./cache.interface.ts";

export function CacheTTL(ttl: number) {
return (_target: any, _methodName: string, descriptor: any) => {
Reflect.defineMetadata(META_CACHE_TTL_KEY, ttl, descriptor.value);
};
}

@Injectable()
export class CacheInterceptor implements NestInterceptor {
ttl: number;
Expand Down Expand Up @@ -70,9 +77,14 @@ export class CacheInterceptor implements NestInterceptor {
}
const result = next();
cache.set(key, result);

const ttl = Reflect.getOwnMetadata(
META_CACHE_TTL_KEY,
options.target[options.methodName],
) || this.ttl;
const st = setTimeout(() => {
cache.delete(key);
}, this.ttl * 1000);
}, ttl * 1000);
Promise.resolve(result)
.then((val) => {
if (this.cacheModuleOptions?.isCacheableValue) {
Expand Down

0 comments on commit 5132b8c

Please sign in to comment.