@marianmeres/kv 1.2.1 → 1.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +133 -0
- package/API.md +624 -0
- package/README.md +10 -2
- package/dist/adapter/abstract.d.ts +5 -0
- package/dist/adapter/abstract.js +5 -0
- package/dist/adapter/deno-kv.d.ts +5 -0
- package/dist/adapter/deno-kv.js +5 -0
- package/dist/adapter/memory.d.ts +5 -0
- package/dist/adapter/memory.js +5 -0
- package/dist/adapter/postgres.d.ts +5 -0
- package/dist/adapter/postgres.js +5 -0
- package/dist/adapter/redis.d.ts +5 -0
- package/dist/adapter/redis.js +5 -0
- package/dist/kv.d.ts +15 -1
- package/dist/kv.js +14 -0
- package/dist/mod.d.ts +32 -0
- package/dist/mod.js +32 -0
- package/dist/utils/sleep.d.ts +5 -0
- package/dist/utils/sleep.js +5 -0
- package/package.json +14 -10
package/AGENTS.md
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# @marianmeres/kv - Agent Reference
|
|
2
|
+
|
|
3
|
+
Machine-friendly reference for AI agents working with this codebase.
|
|
4
|
+
|
|
5
|
+
## Package Identity
|
|
6
|
+
|
|
7
|
+
- **Name**: `@marianmeres/kv`
|
|
8
|
+
- **Version**: 1.2.2
|
|
9
|
+
- **License**: MIT
|
|
10
|
+
- **Runtime**: Deno (primary), Node.js (via npm build)
|
|
11
|
+
- **Language**: TypeScript
|
|
12
|
+
|
|
13
|
+
## Purpose
|
|
14
|
+
|
|
15
|
+
Key-value storage abstraction layer providing a unified Redis-inspired API across multiple storage backends.
|
|
16
|
+
|
|
17
|
+
## Supported Adapters
|
|
18
|
+
|
|
19
|
+
| Adapter | Type String | Required Options | Limitations |
|
|
20
|
+
|---------|-------------|------------------|-------------|
|
|
21
|
+
| Memory | `"memory"` | None | Not persisted |
|
|
22
|
+
| Redis | `"redis"` | `db` (Redis client) | Namespace required; `keys()`/`clear()` unavailable in cluster mode |
|
|
23
|
+
| PostgreSQL | `"postgres"` | `db` (pg.Pool/Client) | None |
|
|
24
|
+
| Deno KV | `"deno-kv"` | `db` (Deno.Kv) | Deno runtime only; `delete()` always true; `expire()`/`ttl()` not supported |
|
|
25
|
+
|
|
26
|
+
## File Structure
|
|
27
|
+
|
|
28
|
+
```
|
|
29
|
+
src/
|
|
30
|
+
├── mod.ts # Main entry point, re-exports kv.ts
|
|
31
|
+
├── kv.ts # Factory function and all exports
|
|
32
|
+
├── adapter/
|
|
33
|
+
│ ├── abstract.ts # Base class + shared types
|
|
34
|
+
│ ├── memory.ts # In-memory adapter
|
|
35
|
+
│ ├── redis.ts # Redis adapter
|
|
36
|
+
│ ├── postgres.ts # PostgreSQL adapter
|
|
37
|
+
│ └── deno-kv.ts # Deno KV adapter
|
|
38
|
+
└── utils/
|
|
39
|
+
└── sleep.ts # Sleep utility function
|
|
40
|
+
|
|
41
|
+
tests/
|
|
42
|
+
├── kv.test.ts # Main test file
|
|
43
|
+
├── _tests-runner.ts # Test harness
|
|
44
|
+
├── _redis.ts # Redis test helper
|
|
45
|
+
└── _pg.ts # PostgreSQL test helper
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Core API
|
|
49
|
+
|
|
50
|
+
### Factory
|
|
51
|
+
|
|
52
|
+
```typescript
|
|
53
|
+
createKVClient(namespace?: string, type?: AdapterType, options?: AdapterOptions): Adapter
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### Client Methods
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
initialize(): Promise<void>
|
|
60
|
+
destroy(hard?: boolean): Promise<void>
|
|
61
|
+
info(): AdapterInfo
|
|
62
|
+
set(key: string, value: any, options?: SetOptions): Promise<boolean>
|
|
63
|
+
get(key: string): Promise<any>
|
|
64
|
+
delete(key: string): Promise<boolean>
|
|
65
|
+
exists(key: string): Promise<boolean>
|
|
66
|
+
keys(pattern: string): Promise<string[]>
|
|
67
|
+
clear(pattern: string): Promise<number>
|
|
68
|
+
setMultiple(pairs: [string, any][], options?: SetOptions): Promise<boolean[]>
|
|
69
|
+
getMultiple(keys: string[]): Promise<Record<string, any>>
|
|
70
|
+
transaction(operations: Operation[]): Promise<any[]>
|
|
71
|
+
expire(key: string, ttl: number): Promise<boolean>
|
|
72
|
+
ttl(key: string): Promise<Date | null | false>
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Key Types
|
|
76
|
+
|
|
77
|
+
```typescript
|
|
78
|
+
interface SetOptions { ttl: number }
|
|
79
|
+
interface AdapterInfo { type: string }
|
|
80
|
+
interface AdapterAbstractOptions { defaultTtl: number; logger?: Logger }
|
|
81
|
+
interface Operation { type: "set" | "get" | "delete"; key: string; value?: any; options?: SetOptions }
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Commands
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
# Run tests (requires --unstable-kv for Deno KV)
|
|
88
|
+
deno test --unstable-kv -A --env-file
|
|
89
|
+
|
|
90
|
+
# Run tests with watch mode
|
|
91
|
+
deno test --unstable-kv -A --env-file --watch
|
|
92
|
+
|
|
93
|
+
# Build npm package
|
|
94
|
+
deno run -A scripts/build-npm.ts
|
|
95
|
+
|
|
96
|
+
# Publish to npm
|
|
97
|
+
deno run -A scripts/build-npm.ts && cd ./.npm-dist && npm publish --access=public
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Test Environment Variables
|
|
101
|
+
|
|
102
|
+
```
|
|
103
|
+
TEST_PG_HOST=localhost
|
|
104
|
+
TEST_PG_PORT=5432
|
|
105
|
+
TEST_PG_DATABASE=<required>
|
|
106
|
+
TEST_PG_USER=<required>
|
|
107
|
+
TEST_PG_PASSWORD=<required>
|
|
108
|
+
TEST_REDIS_URL=redis://localhost:6379
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Implementation Notes
|
|
112
|
+
|
|
113
|
+
1. **Namespace**: Must end with `:` or be empty string
|
|
114
|
+
2. **Value Serialization**: All values JSON-stringified internally
|
|
115
|
+
3. **TTL**: In seconds; stored as absolute Date internally
|
|
116
|
+
4. **Pattern Matching**: Redis-style (`*` = any chars, `?` = single char)
|
|
117
|
+
5. **Transactions**: Atomic for Redis/PostgreSQL; sequential for memory/Deno KV
|
|
118
|
+
|
|
119
|
+
## Dependencies
|
|
120
|
+
|
|
121
|
+
- `@marianmeres/clog` - Logging
|
|
122
|
+
- `pg` - PostgreSQL driver
|
|
123
|
+
- `redis` - Redis client
|
|
124
|
+
|
|
125
|
+
## Extending
|
|
126
|
+
|
|
127
|
+
To add a new adapter:
|
|
128
|
+
1. Create `src/adapter/<name>.ts`
|
|
129
|
+
2. Extend `AdapterAbstract`
|
|
130
|
+
3. Implement all abstract/interface methods
|
|
131
|
+
4. Add to `KnownTypes` in `src/kv.ts`
|
|
132
|
+
5. Add case in `createKVClient` factory
|
|
133
|
+
6. Export from `src/kv.ts`
|
package/API.md
ADDED
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
# @marianmeres/kv API Reference
|
|
2
|
+
|
|
3
|
+
Complete API documentation for the key-value storage abstraction layer.
|
|
4
|
+
|
|
5
|
+
## Table of Contents
|
|
6
|
+
|
|
7
|
+
- [Factory Function](#factory-function)
|
|
8
|
+
- [Client Methods](#client-methods)
|
|
9
|
+
- [Types and Interfaces](#types-and-interfaces)
|
|
10
|
+
- [Adapter-Specific Options](#adapter-specific-options)
|
|
11
|
+
- [Utility Functions](#utility-functions)
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## Factory Function
|
|
16
|
+
|
|
17
|
+
### `createKVClient<T>(namespace?, type?, options?)`
|
|
18
|
+
|
|
19
|
+
Creates and returns a KV client configured for the specified storage backend.
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
function createKVClient<T extends keyof KnownTypes>(
|
|
23
|
+
namespace: string = "",
|
|
24
|
+
type: T = "memory",
|
|
25
|
+
options: Partial<KnownTypes[T]["options"]> = {}
|
|
26
|
+
): KnownTypes[T]["adapter"]
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
**Type Parameters:**
|
|
30
|
+
- `T` - The adapter type (inferred from the `type` parameter)
|
|
31
|
+
|
|
32
|
+
**Parameters:**
|
|
33
|
+
|
|
34
|
+
| Parameter | Type | Default | Description |
|
|
35
|
+
|-----------|------|---------|-------------|
|
|
36
|
+
| `namespace` | `string` | `""` | Key prefix applied to all operations. Must end with `:` or be empty. |
|
|
37
|
+
| `type` | `"memory" \| "redis" \| "postgres" \| "deno-kv"` | `"memory"` | The storage backend to use. |
|
|
38
|
+
| `options` | `Partial<AdapterOptions>` | `{}` | Adapter-specific configuration options. |
|
|
39
|
+
|
|
40
|
+
**Returns:** A configured adapter instance. Call `initialize()` before use.
|
|
41
|
+
|
|
42
|
+
**Throws:**
|
|
43
|
+
- `TypeError` - If namespace doesn't end with `:` (and is not empty)
|
|
44
|
+
- `TypeError` - If an unsupported adapter type is specified
|
|
45
|
+
- `Error` - If `"deno-kv"` is used outside the Deno runtime
|
|
46
|
+
- `Error` - If required options (like `db`) are missing for the adapter
|
|
47
|
+
|
|
48
|
+
**Example:**
|
|
49
|
+
|
|
50
|
+
```typescript
|
|
51
|
+
import { createKVClient } from "@marianmeres/kv";
|
|
52
|
+
|
|
53
|
+
// In-memory storage (great for testing)
|
|
54
|
+
const memoryClient = createKVClient("test:", "memory");
|
|
55
|
+
await memoryClient.initialize();
|
|
56
|
+
|
|
57
|
+
// Redis storage
|
|
58
|
+
import { createClient } from "redis";
|
|
59
|
+
const redisClient = createClient();
|
|
60
|
+
const redis = createKVClient("myapp:", "redis", { db: redisClient });
|
|
61
|
+
await redis.initialize();
|
|
62
|
+
|
|
63
|
+
// PostgreSQL storage
|
|
64
|
+
import pg from "pg";
|
|
65
|
+
const pool = new pg.Pool({ connectionString: "..." });
|
|
66
|
+
const postgres = createKVClient("myapp:", "postgres", { db: pool });
|
|
67
|
+
await postgres.initialize();
|
|
68
|
+
|
|
69
|
+
// Deno KV (Deno runtime only)
|
|
70
|
+
const kv = await Deno.openKv();
|
|
71
|
+
const denoKv = createKVClient("myapp:", "deno-kv", { db: kv });
|
|
72
|
+
await denoKv.initialize();
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## Client Methods
|
|
78
|
+
|
|
79
|
+
All adapter instances implement the following methods:
|
|
80
|
+
|
|
81
|
+
### Lifecycle Methods
|
|
82
|
+
|
|
83
|
+
#### `initialize()`
|
|
84
|
+
|
|
85
|
+
Initializes the adapter and connects to the underlying storage.
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
initialize(): Promise<void>
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Must be called before any other operations. For some adapters (like memory), this is a no-op, but should always be called for consistency.
|
|
92
|
+
|
|
93
|
+
**Throws:** `Error` - If connection fails.
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
#### `destroy(hard?)`
|
|
98
|
+
|
|
99
|
+
Destroys the adapter and releases all resources.
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
destroy(hard?: boolean): Promise<void>
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
**Parameters:**
|
|
106
|
+
|
|
107
|
+
| Parameter | Type | Default | Description |
|
|
108
|
+
|-----------|------|---------|-------------|
|
|
109
|
+
| `hard` | `boolean` | `false` | If `true`, performs a hard cleanup (e.g., drops tables in PostgreSQL). |
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
#### `info()`
|
|
114
|
+
|
|
115
|
+
Returns information about the current adapter instance.
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
info(): AdapterInfo
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
**Returns:** `{ type: string }` - Object containing adapter metadata.
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
const info = client.info();
|
|
125
|
+
console.log(info.type); // "redis", "postgres", "memory", or "deno-kv"
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
### Single Key Operations
|
|
131
|
+
|
|
132
|
+
#### `set(key, value, options?)`
|
|
133
|
+
|
|
134
|
+
Stores a key-value pair in the storage.
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
set(key: string, value: any, options?: Partial<SetOptions>): Promise<boolean>
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Values are automatically serialized to JSON. If the key already exists, it will be overwritten.
|
|
141
|
+
|
|
142
|
+
**Parameters:**
|
|
143
|
+
|
|
144
|
+
| Parameter | Type | Description |
|
|
145
|
+
|-----------|------|-------------|
|
|
146
|
+
| `key` | `string` | The key to store the value under. |
|
|
147
|
+
| `value` | `any` | The value to store. Can be any JSON-serializable value. `undefined` is stored as `null`. |
|
|
148
|
+
| `options` | `Partial<SetOptions>` | Optional settings including TTL. |
|
|
149
|
+
|
|
150
|
+
**Returns:** `Promise<boolean>` - `true` if the operation was successful.
|
|
151
|
+
|
|
152
|
+
**Example:**
|
|
153
|
+
|
|
154
|
+
```typescript
|
|
155
|
+
await client.set("user:123", { name: "John" });
|
|
156
|
+
await client.set("session:abc", { token: "xyz" }, { ttl: 3600 }); // expires in 1 hour
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
#### `get(key)`
|
|
162
|
+
|
|
163
|
+
Retrieves a value by its key.
|
|
164
|
+
|
|
165
|
+
```typescript
|
|
166
|
+
get(key: string): Promise<any>
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
**Parameters:**
|
|
170
|
+
|
|
171
|
+
| Parameter | Type | Description |
|
|
172
|
+
|-----------|------|-------------|
|
|
173
|
+
| `key` | `string` | The key to retrieve. |
|
|
174
|
+
|
|
175
|
+
**Returns:** `Promise<any>` - The stored value, or `null` if the key doesn't exist or has expired.
|
|
176
|
+
|
|
177
|
+
**Example:**
|
|
178
|
+
|
|
179
|
+
```typescript
|
|
180
|
+
const user = await client.get("user:123");
|
|
181
|
+
if (user) {
|
|
182
|
+
console.log(user.name);
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
---
|
|
187
|
+
|
|
188
|
+
#### `delete(key)`
|
|
189
|
+
|
|
190
|
+
Deletes a key from the storage.
|
|
191
|
+
|
|
192
|
+
```typescript
|
|
193
|
+
delete(key: string): Promise<boolean>
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
**Parameters:**
|
|
197
|
+
|
|
198
|
+
| Parameter | Type | Description |
|
|
199
|
+
|-----------|------|-------------|
|
|
200
|
+
| `key` | `string` | The key to delete. |
|
|
201
|
+
|
|
202
|
+
**Returns:** `Promise<boolean>` - `true` if the key existed and was deleted, `false` if it didn't exist.
|
|
203
|
+
|
|
204
|
+
> **Note:** Deno KV always returns `true`, even for non-existent keys.
|
|
205
|
+
|
|
206
|
+
---
|
|
207
|
+
|
|
208
|
+
#### `exists(key)`
|
|
209
|
+
|
|
210
|
+
Checks if a key exists in the storage.
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
exists(key: string): Promise<boolean>
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
**Parameters:**
|
|
217
|
+
|
|
218
|
+
| Parameter | Type | Description |
|
|
219
|
+
|-----------|------|-------------|
|
|
220
|
+
| `key` | `string` | The key to check. |
|
|
221
|
+
|
|
222
|
+
**Returns:** `Promise<boolean>` - `true` if the key exists and hasn't expired.
|
|
223
|
+
|
|
224
|
+
---
|
|
225
|
+
|
|
226
|
+
#### `expire(key, ttl)`
|
|
227
|
+
|
|
228
|
+
Sets a new expiration time on an existing key.
|
|
229
|
+
|
|
230
|
+
```typescript
|
|
231
|
+
expire(key: string, ttl: number): Promise<boolean>
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
**Parameters:**
|
|
235
|
+
|
|
236
|
+
| Parameter | Type | Description |
|
|
237
|
+
|-----------|------|-------------|
|
|
238
|
+
| `key` | `string` | The key to set expiration on. |
|
|
239
|
+
| `ttl` | `number` | Time-to-live in seconds from now. |
|
|
240
|
+
|
|
241
|
+
**Returns:** `Promise<boolean>` - `true` if the expiration was set, `false` if the key doesn't exist.
|
|
242
|
+
|
|
243
|
+
> **Note:** Not supported in Deno KV (always returns `false`).
|
|
244
|
+
|
|
245
|
+
**Example:**
|
|
246
|
+
|
|
247
|
+
```typescript
|
|
248
|
+
await client.set("session:abc", { user: "john" });
|
|
249
|
+
await client.expire("session:abc", 1800); // Expire in 30 minutes
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
---
|
|
253
|
+
|
|
254
|
+
#### `ttl(key)`
|
|
255
|
+
|
|
256
|
+
Gets the expiration time of a key.
|
|
257
|
+
|
|
258
|
+
```typescript
|
|
259
|
+
ttl(key: string): Promise<Date | null | false>
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
**Parameters:**
|
|
263
|
+
|
|
264
|
+
| Parameter | Type | Description |
|
|
265
|
+
|-----------|------|-------------|
|
|
266
|
+
| `key` | `string` | The key to check. |
|
|
267
|
+
|
|
268
|
+
**Returns:**
|
|
269
|
+
- `Date` - The expiration date if TTL is set
|
|
270
|
+
- `null` - If the key exists but has no expiration
|
|
271
|
+
- `false` - If the key doesn't exist or has expired
|
|
272
|
+
|
|
273
|
+
> **Note:** Deno KV always returns `null` (TTL query not supported).
|
|
274
|
+
|
|
275
|
+
**Example:**
|
|
276
|
+
|
|
277
|
+
```typescript
|
|
278
|
+
const expiry = await client.ttl("session:abc");
|
|
279
|
+
if (expiry instanceof Date) {
|
|
280
|
+
console.log(`Expires at: ${expiry.toISOString()}`);
|
|
281
|
+
} else if (expiry === null) {
|
|
282
|
+
console.log("No expiration set");
|
|
283
|
+
} else {
|
|
284
|
+
console.log("Key does not exist");
|
|
285
|
+
}
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
---
|
|
289
|
+
|
|
290
|
+
### Pattern-Based Operations
|
|
291
|
+
|
|
292
|
+
#### `keys(pattern)`
|
|
293
|
+
|
|
294
|
+
Lists all keys matching a pattern.
|
|
295
|
+
|
|
296
|
+
```typescript
|
|
297
|
+
keys(pattern: string): Promise<string[]>
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
Uses Redis-style wildcard patterns:
|
|
301
|
+
- `*` matches any number of characters
|
|
302
|
+
- `?` matches exactly one character
|
|
303
|
+
|
|
304
|
+
**Parameters:**
|
|
305
|
+
|
|
306
|
+
| Parameter | Type | Description |
|
|
307
|
+
|-----------|------|-------------|
|
|
308
|
+
| `pattern` | `string` | The pattern to match keys against (e.g., `"user:*"`, `"session:???"`). |
|
|
309
|
+
|
|
310
|
+
**Returns:** `Promise<string[]>` - Array of matching keys (without namespace prefix), sorted alphabetically.
|
|
311
|
+
|
|
312
|
+
**Throws:** `Error` - In Redis cluster mode.
|
|
313
|
+
|
|
314
|
+
**Example:**
|
|
315
|
+
|
|
316
|
+
```typescript
|
|
317
|
+
const userKeys = await client.keys("user:*");
|
|
318
|
+
const allKeys = await client.keys("*");
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
---
|
|
322
|
+
|
|
323
|
+
#### `clear(pattern)`
|
|
324
|
+
|
|
325
|
+
Deletes all keys matching a pattern.
|
|
326
|
+
|
|
327
|
+
```typescript
|
|
328
|
+
clear(pattern: string): Promise<number>
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
Uses the same pattern syntax as `keys()`.
|
|
332
|
+
|
|
333
|
+
**Parameters:**
|
|
334
|
+
|
|
335
|
+
| Parameter | Type | Description |
|
|
336
|
+
|-----------|------|-------------|
|
|
337
|
+
| `pattern` | `string` | The pattern to match keys against. |
|
|
338
|
+
|
|
339
|
+
**Returns:** `Promise<number>` - The number of keys deleted.
|
|
340
|
+
|
|
341
|
+
**Throws:** `Error` - In Redis cluster mode.
|
|
342
|
+
|
|
343
|
+
**Example:**
|
|
344
|
+
|
|
345
|
+
```typescript
|
|
346
|
+
const deleted = await client.clear("session:*"); // Clear all sessions
|
|
347
|
+
const clearedAll = await client.clear("*"); // Clear everything
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
---
|
|
351
|
+
|
|
352
|
+
### Batch Operations
|
|
353
|
+
|
|
354
|
+
#### `setMultiple(keyValuePairs, options?)`
|
|
355
|
+
|
|
356
|
+
Stores multiple key-value pairs in a single batch operation.
|
|
357
|
+
|
|
358
|
+
```typescript
|
|
359
|
+
setMultiple(keyValuePairs: [string, any][], options?: Partial<SetOptions>): Promise<boolean[]>
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
More efficient than multiple individual `set` calls, especially for Redis and PostgreSQL.
|
|
363
|
+
|
|
364
|
+
**Parameters:**
|
|
365
|
+
|
|
366
|
+
| Parameter | Type | Description |
|
|
367
|
+
|-----------|------|-------------|
|
|
368
|
+
| `keyValuePairs` | `[string, any][]` | Array of `[key, value]` tuples to store. |
|
|
369
|
+
| `options` | `Partial<SetOptions>` | Optional settings applied to all pairs (e.g., TTL). |
|
|
370
|
+
|
|
371
|
+
**Returns:** `Promise<boolean[]>` - Array of boolean results for each operation.
|
|
372
|
+
|
|
373
|
+
**Example:**
|
|
374
|
+
|
|
375
|
+
```typescript
|
|
376
|
+
await client.setMultiple([
|
|
377
|
+
["user:1", { name: "Alice" }],
|
|
378
|
+
["user:2", { name: "Bob" }],
|
|
379
|
+
], { ttl: 3600 });
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
---
|
|
383
|
+
|
|
384
|
+
#### `getMultiple(keys)`
|
|
385
|
+
|
|
386
|
+
Retrieves multiple values in a single batch operation.
|
|
387
|
+
|
|
388
|
+
```typescript
|
|
389
|
+
getMultiple(keys: string[]): Promise<Record<string, any>>
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
More efficient than multiple individual `get` calls.
|
|
393
|
+
|
|
394
|
+
**Parameters:**
|
|
395
|
+
|
|
396
|
+
| Parameter | Type | Description |
|
|
397
|
+
|-----------|------|-------------|
|
|
398
|
+
| `keys` | `string[]` | Array of keys to retrieve. |
|
|
399
|
+
|
|
400
|
+
**Returns:** `Promise<Record<string, any>>` - Object mapping keys to their values. Missing or expired keys will have a value of `null`.
|
|
401
|
+
|
|
402
|
+
**Example:**
|
|
403
|
+
|
|
404
|
+
```typescript
|
|
405
|
+
const users = await client.getMultiple(["user:1", "user:2", "user:3"]);
|
|
406
|
+
// { "user:1": { name: "Alice" }, "user:2": null, "user:3": { name: "Charlie" } }
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
---
|
|
410
|
+
|
|
411
|
+
### Transactions
|
|
412
|
+
|
|
413
|
+
#### `transaction(operations)`
|
|
414
|
+
|
|
415
|
+
Executes multiple operations within a single transaction.
|
|
416
|
+
|
|
417
|
+
```typescript
|
|
418
|
+
transaction(operations: Operation[]): Promise<any[]>
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
For adapters that support it (Redis, PostgreSQL), operations are atomic. For memory and Deno KV, operations are executed sequentially.
|
|
422
|
+
|
|
423
|
+
**Parameters:**
|
|
424
|
+
|
|
425
|
+
| Parameter | Type | Description |
|
|
426
|
+
|-----------|------|-------------|
|
|
427
|
+
| `operations` | `Operation[]` | Array of operations to execute. |
|
|
428
|
+
|
|
429
|
+
**Returns:** `Promise<any[]>` - Array of results for each operation.
|
|
430
|
+
|
|
431
|
+
**Example:**
|
|
432
|
+
|
|
433
|
+
```typescript
|
|
434
|
+
const results = await client.transaction([
|
|
435
|
+
{ type: "set", key: "counter", value: 1 },
|
|
436
|
+
{ type: "get", key: "counter" },
|
|
437
|
+
{ type: "delete", key: "old:key" },
|
|
438
|
+
]);
|
|
439
|
+
// [true, 1, true]
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
---
|
|
443
|
+
|
|
444
|
+
## Types and Interfaces
|
|
445
|
+
|
|
446
|
+
### `SetOptions`
|
|
447
|
+
|
|
448
|
+
Options for the `set` operation.
|
|
449
|
+
|
|
450
|
+
```typescript
|
|
451
|
+
interface SetOptions {
|
|
452
|
+
/** Time-to-live in seconds. After this time, the key will expire. */
|
|
453
|
+
ttl: number;
|
|
454
|
+
}
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
---
|
|
458
|
+
|
|
459
|
+
### `AdapterInfo`
|
|
460
|
+
|
|
461
|
+
Information about the adapter instance.
|
|
462
|
+
|
|
463
|
+
```typescript
|
|
464
|
+
interface AdapterInfo {
|
|
465
|
+
/** The adapter type identifier. */
|
|
466
|
+
type: string; // "redis" | "postgres" | "memory" | "deno-kv"
|
|
467
|
+
}
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
---
|
|
471
|
+
|
|
472
|
+
### `AdapterAbstractOptions`
|
|
473
|
+
|
|
474
|
+
Base options shared by all adapter implementations.
|
|
475
|
+
|
|
476
|
+
```typescript
|
|
477
|
+
interface AdapterAbstractOptions {
|
|
478
|
+
/** Default TTL in seconds applied to all set operations when not explicitly specified. Set to 0 to disable. */
|
|
479
|
+
defaultTtl: number;
|
|
480
|
+
/** Optional logger instance for debugging and error logging. */
|
|
481
|
+
logger?: Logger;
|
|
482
|
+
}
|
|
483
|
+
```
|
|
484
|
+
|
|
485
|
+
---
|
|
486
|
+
|
|
487
|
+
### `Operation`
|
|
488
|
+
|
|
489
|
+
Represents a single operation within a transaction.
|
|
490
|
+
|
|
491
|
+
```typescript
|
|
492
|
+
interface Operation {
|
|
493
|
+
/** The type of operation to perform. */
|
|
494
|
+
type: "set" | "get" | "delete";
|
|
495
|
+
/** The key to operate on. */
|
|
496
|
+
key: string;
|
|
497
|
+
/** The value to set (only used for "set" operations). */
|
|
498
|
+
value?: any;
|
|
499
|
+
/** Optional settings for the operation (only used for "set" operations). */
|
|
500
|
+
options?: Partial<SetOptions>;
|
|
501
|
+
}
|
|
502
|
+
```
|
|
503
|
+
|
|
504
|
+
---
|
|
505
|
+
|
|
506
|
+
## Adapter-Specific Options
|
|
507
|
+
|
|
508
|
+
### `AdapterMemoryOptions`
|
|
509
|
+
|
|
510
|
+
```typescript
|
|
511
|
+
interface AdapterMemoryOptions extends AdapterAbstractOptions {
|
|
512
|
+
/**
|
|
513
|
+
* Interval in seconds for automatic cleanup of expired keys.
|
|
514
|
+
* Set to 0 to disable automatic cleanup (expired keys will still be
|
|
515
|
+
* lazily removed on access).
|
|
516
|
+
*/
|
|
517
|
+
ttlCleanupIntervalSec: number;
|
|
518
|
+
}
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
---
|
|
522
|
+
|
|
523
|
+
### `AdapterRedisOptions`
|
|
524
|
+
|
|
525
|
+
```typescript
|
|
526
|
+
interface AdapterRedisOptions extends AdapterAbstractOptions {
|
|
527
|
+
/**
|
|
528
|
+
* Redis client instance created via `createClient()` or `createClientPool()`.
|
|
529
|
+
* Pool support is experimental and not fully tested.
|
|
530
|
+
*/
|
|
531
|
+
db: ReturnType<typeof createClient> | ReturnType<typeof createClientPool>;
|
|
532
|
+
/**
|
|
533
|
+
* Set to `true` if connecting to a Redis Cluster.
|
|
534
|
+
* Note: `keys()` and `clear()` operations are not supported in cluster mode.
|
|
535
|
+
*/
|
|
536
|
+
isCluster: boolean;
|
|
537
|
+
}
|
|
538
|
+
```
|
|
539
|
+
|
|
540
|
+
**Important:** Namespace is required for Redis adapter (cannot be empty string).
|
|
541
|
+
|
|
542
|
+
---
|
|
543
|
+
|
|
544
|
+
### `AdapterPostgresOptions`
|
|
545
|
+
|
|
546
|
+
```typescript
|
|
547
|
+
interface AdapterPostgresOptions extends AdapterAbstractOptions {
|
|
548
|
+
/** PostgreSQL connection instance - either `pg.Pool` or `pg.Client`. */
|
|
549
|
+
db: pg.Pool | pg.Client;
|
|
550
|
+
/**
|
|
551
|
+
* Name of the table to use for storing key-value pairs.
|
|
552
|
+
* The table will be created automatically if it doesn't exist.
|
|
553
|
+
* @default "__kv"
|
|
554
|
+
*/
|
|
555
|
+
tableName: string;
|
|
556
|
+
/**
|
|
557
|
+
* Interval in seconds for automatic cleanup of expired keys.
|
|
558
|
+
* Set to 0 to disable automatic cleanup.
|
|
559
|
+
*/
|
|
560
|
+
ttlCleanupIntervalSec: number;
|
|
561
|
+
}
|
|
562
|
+
```
|
|
563
|
+
|
|
564
|
+
**Table Schema:**
|
|
565
|
+
- `key` (VARCHAR 512) - Primary key
|
|
566
|
+
- `value` (JSONB) - Stored value
|
|
567
|
+
- `expires_at` (TIMESTAMP WITH TIME ZONE) - Expiration time
|
|
568
|
+
- `created_at` (TIMESTAMP WITH TIME ZONE) - Creation time
|
|
569
|
+
- `updated_at` (TIMESTAMP WITH TIME ZONE) - Last update time
|
|
570
|
+
|
|
571
|
+
---
|
|
572
|
+
|
|
573
|
+
### `AdapterDenoKvOptions`
|
|
574
|
+
|
|
575
|
+
```typescript
|
|
576
|
+
interface AdapterDenoKvOptions extends AdapterAbstractOptions {
|
|
577
|
+
/**
|
|
578
|
+
* Deno.Kv instance obtained via `Deno.openKv()`.
|
|
579
|
+
*/
|
|
580
|
+
db: Deno.Kv;
|
|
581
|
+
}
|
|
582
|
+
```
|
|
583
|
+
|
|
584
|
+
**Limitations:**
|
|
585
|
+
- Only works in Deno runtime
|
|
586
|
+
- `delete()` always returns `true` (Deno.Kv limitation)
|
|
587
|
+
- `expire()` is not supported (always returns `false`)
|
|
588
|
+
- `ttl()` is not supported (always returns `null`)
|
|
589
|
+
- TTL can be set during `set()` but cannot be queried afterward
|
|
590
|
+
|
|
591
|
+
---
|
|
592
|
+
|
|
593
|
+
## Utility Functions
|
|
594
|
+
|
|
595
|
+
### `sleep(timeout, __timeout_ref__?)`
|
|
596
|
+
|
|
597
|
+
Delays execution for the specified number of milliseconds.
|
|
598
|
+
|
|
599
|
+
```typescript
|
|
600
|
+
function sleep(
|
|
601
|
+
timeout: number,
|
|
602
|
+
__timeout_ref__?: { id: number }
|
|
603
|
+
): Promise<void>
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
**Parameters:**
|
|
607
|
+
|
|
608
|
+
| Parameter | Type | Default | Description |
|
|
609
|
+
|-----------|------|---------|-------------|
|
|
610
|
+
| `timeout` | `number` | - | The delay in milliseconds. |
|
|
611
|
+
| `__timeout_ref__` | `{ id: number }` | `{ id: -1 }` | Optional reference object to capture the timeout ID for cleanup. |
|
|
612
|
+
|
|
613
|
+
**Example:**
|
|
614
|
+
|
|
615
|
+
```typescript
|
|
616
|
+
import { sleep } from "@marianmeres/kv";
|
|
617
|
+
|
|
618
|
+
await sleep(1000); // Wait 1 second
|
|
619
|
+
|
|
620
|
+
// With timeout reference for cleanup
|
|
621
|
+
const ref = { id: -1 };
|
|
622
|
+
const sleepPromise = sleep(5000, ref);
|
|
623
|
+
// Later: clearTimeout(ref.id);
|
|
624
|
+
```
|
package/README.md
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
# @marianmeres/kv
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@marianmeres/kv)
|
|
4
|
+
[](https://jsr.io/@marianmeres/kv)
|
|
5
|
+
[](https://opensource.org/licenses/MIT)
|
|
6
|
+
|
|
7
|
+
Key-value storage abstraction layer with support for multiple backend adapters:
|
|
4
8
|
- redis
|
|
5
9
|
- postgresql
|
|
6
10
|
- memory
|
|
@@ -75,4 +79,8 @@ client.ttl(key: string): Promise<Date | null | false>
|
|
|
75
79
|
|
|
76
80
|
### Memory
|
|
77
81
|
- Data is not persisted (in-memory only)
|
|
78
|
-
- Supports optional TTL cleanup via `ttlCleanupIntervalSec` option
|
|
82
|
+
- Supports optional TTL cleanup via `ttlCleanupIntervalSec` option
|
|
83
|
+
|
|
84
|
+
## Full API Reference
|
|
85
|
+
|
|
86
|
+
For complete API documentation including all methods, types, and adapter-specific options, see [API.md](API.md).
|
package/dist/adapter/abstract.js
CHANGED
package/dist/adapter/deno-kv.js
CHANGED
package/dist/adapter/memory.d.ts
CHANGED
package/dist/adapter/memory.js
CHANGED
package/dist/adapter/postgres.js
CHANGED
package/dist/adapter/redis.d.ts
CHANGED
package/dist/adapter/redis.js
CHANGED
package/dist/kv.d.ts
CHANGED
|
@@ -1,7 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module
|
|
3
|
+
*
|
|
4
|
+
* Factory module for creating KV client instances.
|
|
5
|
+
*
|
|
6
|
+
* Exports the main {@link createKVClient} factory function and re-exports
|
|
7
|
+
* all adapter classes, types, and interfaces.
|
|
8
|
+
*/
|
|
1
9
|
import { AdapterDenoKv, type AdapterDenoKvOptions } from "./adapter/deno-kv.js";
|
|
2
10
|
import { AdapterMemory, type AdapterMemoryOptions } from "./adapter/memory.js";
|
|
3
11
|
import { AdapterPostgres, type AdapterPostgresOptions } from "./adapter/postgres.js";
|
|
4
12
|
import { AdapterRedis, type AdapterRedisOptions } from "./adapter/redis.js";
|
|
13
|
+
export type { SetOptions, AdapterInfo, AdapterAbstractOptions, Operation } from "./adapter/abstract.js";
|
|
14
|
+
export { AdapterAbstract } from "./adapter/abstract.js";
|
|
15
|
+
export { AdapterMemory, type AdapterMemoryOptions } from "./adapter/memory.js";
|
|
16
|
+
export { AdapterRedis, type AdapterRedisOptions } from "./adapter/redis.js";
|
|
17
|
+
export { AdapterPostgres, type AdapterPostgresOptions } from "./adapter/postgres.js";
|
|
18
|
+
export { AdapterDenoKv, type AdapterDenoKvOptions } from "./adapter/deno-kv.js";
|
|
19
|
+
export { sleep } from "./utils/sleep.js";
|
|
5
20
|
/**
|
|
6
21
|
* Type mapping for all supported KV adapter types.
|
|
7
22
|
* @internal
|
|
@@ -73,4 +88,3 @@ interface KnownTypes {
|
|
|
73
88
|
* ```
|
|
74
89
|
*/
|
|
75
90
|
export declare function createKVClient<T extends keyof KnownTypes>(namespace?: string, type?: T, options?: Partial<KnownTypes[T]["options"]>): KnownTypes[T]["adapter"];
|
|
76
|
-
export {};
|
package/dist/kv.js
CHANGED
|
@@ -1,7 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module
|
|
3
|
+
*
|
|
4
|
+
* Factory module for creating KV client instances.
|
|
5
|
+
*
|
|
6
|
+
* Exports the main {@link createKVClient} factory function and re-exports
|
|
7
|
+
* all adapter classes, types, and interfaces.
|
|
8
|
+
*/
|
|
1
9
|
import { AdapterDenoKv } from "./adapter/deno-kv.js";
|
|
2
10
|
import { AdapterMemory } from "./adapter/memory.js";
|
|
3
11
|
import { AdapterPostgres, } from "./adapter/postgres.js";
|
|
4
12
|
import { AdapterRedis } from "./adapter/redis.js";
|
|
13
|
+
export { AdapterAbstract } from "./adapter/abstract.js";
|
|
14
|
+
export { AdapterMemory } from "./adapter/memory.js";
|
|
15
|
+
export { AdapterRedis } from "./adapter/redis.js";
|
|
16
|
+
export { AdapterPostgres } from "./adapter/postgres.js";
|
|
17
|
+
export { AdapterDenoKv } from "./adapter/deno-kv.js";
|
|
18
|
+
export { sleep } from "./utils/sleep.js";
|
|
5
19
|
/**
|
|
6
20
|
* Factory function to create a KV client with the specified adapter type.
|
|
7
21
|
*
|
package/dist/mod.d.ts
CHANGED
|
@@ -1 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module
|
|
3
|
+
*
|
|
4
|
+
* Key-value storage abstraction layer with support for multiple backend adapters.
|
|
5
|
+
*
|
|
6
|
+
* This module provides a unified API for key-value operations across different storage backends:
|
|
7
|
+
* - **memory** - In-memory storage (default, not persisted)
|
|
8
|
+
* - **redis** - Redis server
|
|
9
|
+
* - **postgres** - PostgreSQL database
|
|
10
|
+
* - **deno-kv** - Deno KV (Deno runtime only)
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* import { createKVClient } from "@marianmeres/kv";
|
|
15
|
+
*
|
|
16
|
+
* // Create an in-memory client
|
|
17
|
+
* const client = createKVClient("myapp:", "memory");
|
|
18
|
+
* await client.initialize();
|
|
19
|
+
*
|
|
20
|
+
* // Basic operations
|
|
21
|
+
* await client.set("user:123", { name: "John" });
|
|
22
|
+
* const user = await client.get("user:123");
|
|
23
|
+
* await client.delete("user:123");
|
|
24
|
+
*
|
|
25
|
+
* // Pattern matching
|
|
26
|
+
* const keys = await client.keys("user:*");
|
|
27
|
+
* await client.clear("session:*");
|
|
28
|
+
*
|
|
29
|
+
* // Cleanup
|
|
30
|
+
* await client.destroy();
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
1
33
|
export * from "./kv.js";
|
package/dist/mod.js
CHANGED
|
@@ -1 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module
|
|
3
|
+
*
|
|
4
|
+
* Key-value storage abstraction layer with support for multiple backend adapters.
|
|
5
|
+
*
|
|
6
|
+
* This module provides a unified API for key-value operations across different storage backends:
|
|
7
|
+
* - **memory** - In-memory storage (default, not persisted)
|
|
8
|
+
* - **redis** - Redis server
|
|
9
|
+
* - **postgres** - PostgreSQL database
|
|
10
|
+
* - **deno-kv** - Deno KV (Deno runtime only)
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* import { createKVClient } from "@marianmeres/kv";
|
|
15
|
+
*
|
|
16
|
+
* // Create an in-memory client
|
|
17
|
+
* const client = createKVClient("myapp:", "memory");
|
|
18
|
+
* await client.initialize();
|
|
19
|
+
*
|
|
20
|
+
* // Basic operations
|
|
21
|
+
* await client.set("user:123", { name: "John" });
|
|
22
|
+
* const user = await client.get("user:123");
|
|
23
|
+
* await client.delete("user:123");
|
|
24
|
+
*
|
|
25
|
+
* // Pattern matching
|
|
26
|
+
* const keys = await client.keys("user:*");
|
|
27
|
+
* await client.clear("session:*");
|
|
28
|
+
*
|
|
29
|
+
* // Cleanup
|
|
30
|
+
* await client.destroy();
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
1
33
|
export * from "./kv.js";
|
package/dist/utils/sleep.d.ts
CHANGED
package/dist/utils/sleep.js
CHANGED
package/package.json
CHANGED
|
@@ -1,25 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marianmeres/kv",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/mod.js",
|
|
6
6
|
"types": "dist/mod.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/mod.d.ts",
|
|
10
|
+
"import": "./dist/mod.js"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
7
13
|
"author": "Marian Meres",
|
|
8
14
|
"license": "MIT",
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"@marianmeres/clog": "^3.15.0",
|
|
17
|
+
"@types/pg": "^8.16.0",
|
|
18
|
+
"@types/redis": "^4.0.10",
|
|
19
|
+
"pg": "^8.16.3",
|
|
20
|
+
"redis": "^5.10.0"
|
|
21
|
+
},
|
|
9
22
|
"repository": {
|
|
10
23
|
"type": "git",
|
|
11
24
|
"url": "git+https://github.com/marianmeres/kv.git"
|
|
12
25
|
},
|
|
13
26
|
"bugs": {
|
|
14
27
|
"url": "https://github.com/marianmeres/kv/issues"
|
|
15
|
-
},
|
|
16
|
-
"dependencies": {
|
|
17
|
-
"@marianmeres/clog": "^3.0.0",
|
|
18
|
-
"pg": "^8.16.3",
|
|
19
|
-
"redis": "^5.10.0"
|
|
20
|
-
},
|
|
21
|
-
"devDependencies": {
|
|
22
|
-
"@types/node": "latest",
|
|
23
|
-
"@types/pg": "latest"
|
|
24
28
|
}
|
|
25
29
|
}
|