k.cache
Site-wide in-memory cache, shared across requests within the same site
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
| KScript APIs, Page / Layout / View server scripts | In-memory server cache isolated per site | Cache expensive queries, API results, and external asset URLs |
k.cache stores key-value pairs in server memory, isolated per current site (grouped internally by site ID). On a cache miss, get() returns undefined (pair with containsKey() when cached values may be falsy).
Quick Start
k.api.get(() => {
const key = "summary-" + (k.request.queryString.get("id") || "default")
return k.cache.getOrCreate(
key,
() => ({ generatedAt: Date.now(), ok: true }),
300
)
})Quick Reference
| Method / Property | Description | Returns |
|---|---|---|
group | Read-only opaque cache group identifier for current site | string |
set(key, value[, seconds | options]) | Store entry in cache (2 args default ~120 minutes) | void |
get(key) | Read cached entry; returns undefined on miss | any |
getOrCreate(key, factory[, seconds | options]) | Compute, store, and return entry on cache miss | any |
containsKey(key) | Check whether cache key exists | boolean |
remove(key) | Delete a single cache entry | void |
removeAll() | Invalidate current site entries stored via set(key, value[, seconds]) or getOrCreate(..., seconds) | void |
localCache(externalUrl, hours) | Register external URL and return local site URL (fetched and cached on first request) | string |
getOrSet(key, script, TimeOutMinutes) | Applies duration in seconds; returns undefined on miss (use getOrCreate instead) | any |
Differences from k.session
| API | Storage | Typical uses |
|---|---|---|
k.cache | Site in-memory cache with optional TTL in seconds | Hot data, computed results, site-wide sharing |
k.session | Visitor-scoped session storage | Shopping carts, pre-login visitor state |
group
Read-only group identifier used by the current site's cache. It stays stable within the same site and isolates cache keys from other sites. Treat it as an opaque string; do not parse it or depend on its format.
Returns: string.
k.api.get(() => {
return { group: k.cache.group }
})set()
Write an entry to the cache.
| Overload | Description |
|---|---|
set(key, value, seconds) | Expires after seconds (absolute expiration) |
set(key, value) | Defaults to approximately 120 minutes |
set(key, value, options) | Configures expiration through an Options object |
Keys can be up to 1024 characters long. The seconds argument in set(key, value, seconds) is capped by the server's Cache:MaxExpireSeconds setting (about 2 hours by default).
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Cache key |
value | any | Yes | Value to cache |
seconds | number | No | Expiration in seconds |
options | Options | No | Expiration options object |
Returns: void.
k.api.post(() => {
const key = "summary-" + Date.now()
k.cache.set(key, { ok: true }, 60)
return {
stored: k.cache.containsKey(key),
value: k.cache.get(key)
}
})Options Overload (set / getOrCreate)
When passing an Options object as the third argument, you can pass absoluteExpiration or slidingExpiration. Both properties map to C# TimeSpan? and expect TimeSpan string format (such as "00:05:00" for 5 minutes) or null — do not pass numeric seconds.
set(key, value, seconds)automatically binds the current site cascade token and absolute expiration, and is the recommended form for regular script caching.Cascadecannot be constructed from a plain JavaScript object literal (passing{ cascades: [...] }throws a missing-constructor error), so omitcascadesfrom script option literals. Because theOptionsoverloads (set(key, value, options)andgetOrCreate(key, factory, options)) do not attach the site's cascade token automatically,removeAll()will NOT clear entries written viaOptions; remove them explicitly withremove(key)or let them expire viaoptions.
k.api.post(() => {
const key = "opt-" + Date.now()
k.cache.set(key, { ok: true }, { absoluteExpiration: "00:05:00", slidingExpiration: null })
const value = k.cache.get(key)
k.cache.remove(key)
return { value }
})get()
Read a cached value; returns undefined when missing.
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Cache key |
Returns: any, the cached value, or undefined on a miss.
k.api.get(() => {
const key = k.request.queryString.get("key")
return k.cache.get(key)
})getOrCreate()
Execute factory on a cache miss, store the result, and return it.
| Overload | Description |
|---|---|
getOrCreate(key, factory, seconds) | Expiration in seconds (most common) |
getOrCreate(key, factory, options?) | Uses an Options configuration object |
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Cache key |
factory | Function | Yes | Factory callback invoked on a miss; its return value is cached |
seconds | number | No | Expiration in seconds |
options | Options | No | Expiration options object |
Returns: any, the cached value or newly created value returned by factory.
k.api.get(() => {
const id = k.request.queryString.get("id") || "default"
const key = "expensive-" + id
const value = k.cache.getOrCreate(
key,
() => {
return { computedAt: Date.now(), id }
},
300
)
return value
})containsKey()
Check whether a cache key exists.
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Cache key |
Returns: boolean.
k.api.get(() => {
return { exists: k.cache.containsKey("my-key") }
})remove() / removeAll()
remove(key) deletes one entry; removeAll() invalidates entries for the current site stored via set(key, value), set(key, value, seconds), or getOrCreate(key, factory, seconds) (it does not clear entries written via the Options overload, which must be deleted with remove(key) or expire via options).
| Method | Parameters | Returns | Description |
|---|---|---|---|
remove(key) | key: string | void | Delete one cached entry |
removeAll() | None | void | Clear site-cascaded cache entries (excludes Options overload entries) |
k.api.post(() => {
const key = "rm-" + Date.now()
k.cache.set(key, 1, 60)
k.cache.remove(key)
return { exists: k.cache.containsKey(key) }
})localCache()
Registers an external URL for local site caching and returns a local site URL. Calling localCache() does not trigger an eager download; the resource is fetched and cached on demand when the returned local URL is first requested.
| Parameter | Type | Required | Description |
|---|---|---|---|
externalUrl | string | Yes | External resource URL |
hours | number | Yes | Local cache lifetime in hours |
Returns: string, a local site URL.
k.api.get(() => {
const url = k.cache.localCache("https://example.com/asset.png", 24)
return { localUrl: url }
})getOrSet()
Read or cache a value by script line. Although the parameter is named TimeOutMinutes, the value is forwarded directly as seconds to set(key, obj, seconds); additionally, on a cache miss get(key) returns undefined (non-null in the underlying runtime), so calling getOrSet() on an uncached key returns undefined without executing scriptOrFunctionName. For factory-computed caching, use getOrCreate().
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Cache key |
scriptOrFunctionName | string | Yes | Script expression string |
TimeOutMinutes | number | Yes | Duration (applied in seconds) |
Returns: any, the cached value on a hit, or undefined on a miss.
// Recommended alternative using getOrCreate:
const data = k.cache.getOrCreate("report-summary", () => {
return k.DB.sqlite.query("SELECT 1")
}, 1800)TypeScript Definitions
interface KCache extends MemoryCacheBase {
readonly group: string;
set(key: string, value: any, seconds: number): void;
set(key: string, value: any): void;
set(key: string, value: any, options: Options): void;
get(key: string): any;
getOrCreate(key: string, factory: Function, seconds: number): any;
getOrCreate(key: string, factory: any, options?: Options): any;
remove(key: string): void;
removeAll(): void;
containsKey(key: string): boolean;
localCache(externalUrl: string, hours: number): string;
getOrSet(key: string, scriptOrFunctionName: string, TimeOutMinutes: number): any;
}
interface Options {
absoluteExpiration?: string | null; // C# TimeSpan? string format, e.g. "00:05:00"
slidingExpiration?: string | null; // C# TimeSpan? string format, e.g. "00:01:00"
cascades?: Cascade[];
}
interface Cascade {
key: string;
removeChangeToken: boolean;
}