# Cache

## Members

### `policy : Map<string|RegExp, number>`

The cache policies that this application uses.

### `storage : any`

Any object that can be used as storage, valid values can be `{}`, `window.localStorage`, `window.sessionStorage` or any class that can be used as a key/value storage.

## Methods

### `constructor(storage)`

Create a cache instance that can be used in the SDK.

* `storage` should match the [`storage`](#storage-any) member;

```javascript
const myCache = new Cache(window.localStorage)
```

### `async cache(key, callback)`

Attempt to get a cached value based on a key, it is not found in the cache, create it from the callback function.

{% hint style="info" %}
The callback function can be asynchronous.
{% endhint %}

```javascript
const value = await myCache.cache('key', () => 'value')
```

### `invalidate(key)`

Remove a key or a cache group from the cache.

* `key` must be a string that matches the cache key or a regular expression;

```javascript
myCache.invalidate('key')

// ... or

myCache.invalidate(/^key/)
```

### `addPolicy(key, lifespan)`

Add a new cache policy to the cache object.

* `key` must be a string that matches the cache key or a regular expression;
* `lifespan` specifies for how long the cache object should be valid in seconds;

```javascript
myCache.addPolicy('key', 300) // keep the object for 5 minutes

// ... or

myCache.addPolicy(/^key/, 300) // the same length as above but as a regex
```

### `static use(cacheBuilder)`

Use a specific cache object for the global cache.

* `cacheBuilder` must be a function that returns `Cache`;

```javascript
Cache.use(() => myCache)

// ... or

Cache.use(() => new Cache(window.sessionStorage)
    .addPolicy(/^key/, 300)
    .addPolicy('other', 5))
```

### `static get()`

Get the global cache object.

```javascript
const globalCache = Cache.get()
```

## Helpers

### `async function cache(key, callback)`

Cache something globally.

{% hint style="info" %}
This function is an alias for [`Cache.get().cache(key, callback)`](#async-cache-key-callback).
{% endhint %}

```javascript
const value = await cache('key', () => 'value')
```

### `function invalidate(key)`

Invalidate something from global cache.

{% hint style="info" %}
This function is an alias for [`Cache.get().invalidate(key)`](#invalidate-key).
{% endhint %}

### `escapePolicyPart(string)`

Escape a variable to be used in a regex.

```javascript
const value = '/-/' // this cannot be used in a regex without modifying it
const escapedValue = escapePoliciyPart(value)
```
