# KvCollection

`class` in `core` · v0.12.1

<https://seedcord.org/docs/packages/core/0.12.1/classes/kv-collection>

The records of one type, stored under one name in `config.kv`. Get one from
`kv.collection<T>('name')`.

Every record goes through JSON on its way in and out. A `Date` you store reads back from `get()`
as an ISO string.

```ts
class KvCollection<TRecord>
```

## Examples

```ts
interface Profile { bio: string; joinedAt: Date }
const profiles = this.core.kv.collection<Profile>('profile');

await profiles.set(user.id, { bio: 'hi', joinedAt: new Date() });
const profile = await profiles.get(user.id); // { bio: string; joinedAt: string } | undefined
await profiles.delete(user.id);
```

## Constructors

### constructor

```ts
KvCollection(
    driver: KvDriver,
    prefix: string,
    updates: KeyedQueue
)
```

Constructs a new instance of the `KvCollection` class

## Methods

### delete

```ts
public async delete(id: string): Promise<void>
```

Removes the record under `id`.

### entries

```ts
public entries(): AsyncIterable<
    [id: string, record: Stored<TRecord>]
>
```

Yields `[id, record]` for every record in this collection that hasn't expired. Use it to read
back what the bot saved before a restart.

### get

```ts
public async get(
    id: string
): Promise<Stored<TRecord> | undefined>
```

Reads the record stored under `id`. Resolves to `undefined` when nothing is there or the record expired.

### set

```ts
public async set(
    id: string,
    value: TRecord,
    ttlMs?: number
): Promise<void>
```

Stores `value` under `id` and replaces whatever was there.

### update

```ts
public async update(
    id: string,
    next: (current: Stored<TRecord> | undefined) => TRecord,
    ttlMs?: number | ((value: TRecord) => number)
): Promise<TRecord>
```

Stores what `next` returns for the record under `id`, then resolves to that value. `next` gets
the current record, or `undefined` when there is none.

Use it over a `get()` then a `set()` when two calls can change one record at the same time.
`set()`, `delete()`, and `update()` calls on one id run one after the other in this process.
None of them loses another's change. Two processes sharing one backend can still both read
before either writes.
