interface ExpiringValue<T> {
value: T;
expires: number;
}
// Cloudflare cache namespaces
export const MY_KV_NAMESPACE = 'myservice.internal/v1'
export const MY_CACHE_NAMESPACE = 'https://' + FLAME_KV_NAMESPACE
// These types let you operate on an in-memory cache stored in a Map
/**
* Get a value from cache
* @param store Store to access
* @param key Lookup key
* @returns Stored type
*/
export function cget<T>(store: Map<string, ExpiringValue<T>>, key: string): T | undefined {
const val = store.get(key)
if (!val) return undefined
if(val.expires < (Date.now() / 1000)) {
store.delete(key)
return undefined
}
return val.value
}
/**
* Store a value in cache
* @param store Store to access
* @param key Lookup key
* @param value Value to store
* @param ttl Time to live in seconds
*/
export function cset<T>(store: Map<string, ExpiringValue<T>>, key: string, value: T, ttl: number) {
store.set(key, {
expires: (Date.now() / 1000) + ttl,
value
})
}
/**
* Delete a value in cache
* @param store Store to access
* @param key Lookup key
*/
export function cdel<T>(store: Map<string, ExpiringValue<T>>, key: string) {
store.delete(key)
}
interface ExpiringValue<T> {
value: T;
expires: number;
}
// Cloudflare cache namespaces
export const MY_KV_NAMESPACE = 'myservice.internal/v1'
export const MY_CACHE_NAMESPACE = 'https://' + FLAME_KV_NAMESPACE
// These types let you operate on an in-memory cache stored in a Map
/**
* Get a value from cache
* @param store Store to access
* @param key Lookup key
* @returns Stored type
*/
export function cget<T>(store: Map<string, ExpiringValue<T>>, key: string): T | undefined {
const val = store.get(key)
if (!val) return undefined
if(val.expires < (Date.now() / 1000)) {
store.delete(key)
return undefined
}
return val.value
}
/**
* Store a value in cache
* @param store Store to access
* @param key Lookup key
* @param value Value to store
* @param ttl Time to live in seconds
*/
export function cset<T>(store: Map<string, ExpiringValue<T>>, key: string, value: T, ttl: number) {
store.set(key, {
expires: (Date.now() / 1000) + ttl,
value
})
}
/**
* Delete a value in cache
* @param store Store to access
* @param key Lookup key
*/
export function cdel<T>(store: Map<string, ExpiringValue<T>>, key: string) {
store.delete(key)
}