Rest API
can be cached by using @Cacheable
decorator
Rest API Caching
@Rest("/todos")
export class TodoRest {
constructor(
private _service: TodoService,
@CacheEventLookup() readonly _cacheEvent: CacheEventHandler
) {}
@Get({ uri: "/:id" })
@Cacheable({ ttl: 300, key: async (todo: TodoModel) => `/todos/${todo.id}` })
public async getTodoById(
@Param("id") id: number,
@Query("filter") test: string
): Promise<any> {
return await this._service.getById(id);
}
}
When using key
property of @Cacheable
args as a function this value will be used for build the cache key only.
- The key for acquiring data from
CacheStore
is arequest uri
if key property is a async function. - The key for acquiring data from
CacheStore
is the key value if key property is a string.
Parameters | Description | Note |
---|---|---|
ttl | Time to Live | based on the default cache store (second/millis) |
key | Key can be string or a Promise<string> | the Promise key has a arg which is the return data of the function |
validate | Validate the data before cached | all undefined or empty array is prohibited by default |
Eviction
@Evict
has 1 arg and accept wildcard.
*
will clean all cached data/<uri>/*
will clear the cached data related to this uri.
@Rest("/todos")
export class TodoRest {
private readonly _cacheStore?: CacheManager;
constructor(
private _service: TodoService,
@CacheLookup() readonly cacheStore: CacheStore,
@CacheEventLookup() readonly _cacheEvent: CacheEventHandler
) {
this._cacheStore = cacheStore.get();
}
@Get({ uri: "/:id" })
@Guard({ roles: ["admin", "moderator"], permissions: ["add-user"] })
@Evict({ key: "/todos/*" }) // evict has 1 arg and accept wildcard. with '*' will clean all cached data and '/<uri>/*' will clear all cache for this uri only
public async getTodoById(
@Param("id") id: number,
@Query("filter") test: string
): Promise<any> {
return await this._service.getById(id);
}
}
Manual
submit
and evict
cache by acquire CacheEventHandler
through @CacheEventLookup
. (Event Driven Pattern)
or acquire CacheStore
through @CacheLookup
@Rest("/todos")
export class TodoRest {
private readonly _cacheStore?: CacheManager;
constructor(
private _service: TodoService,
@CacheLookup() readonly cacheStore: CacheStore,
@CacheEventLookup() readonly _cacheEvent: CacheEventHandler
) {
this._cacheStore = cacheStore.get();
}
}