@temps-sdk/kv 0.0.1 → 0.0.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/README.md +312 -0
- package/package.json +1 -1
package/README.md
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/gotempsh/temps/refs/heads/main/web/public/logo/temps-logo-light.png" alt="Temps Platform" width="700" />
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<h1 align="center">@temps-sdk/kv</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<a href="https://www.npmjs.com/package/@temps-sdk/kv"><img src="https://img.shields.io/npm/v/@temps-sdk/kv.svg" alt="npm version" /></a>
|
|
9
|
+
<a href="https://www.npmjs.com/package/@temps-sdk/kv"><img src="https://img.shields.io/npm/dm/@temps-sdk/kv.svg" alt="npm downloads" /></a>
|
|
10
|
+
<a href="https://github.com/AnomalyCo/temps/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/@temps-sdk/kv.svg" alt="license" /></a>
|
|
11
|
+
</p>
|
|
12
|
+
|
|
13
|
+
<p align="center">
|
|
14
|
+
Serverless key-value store for Temps projects. Store and retrieve JSON-serializable data with expiration, atomic increments, and pattern matching -- no infrastructure to manage.
|
|
15
|
+
</p>
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
# npm
|
|
21
|
+
npm install @temps-sdk/kv
|
|
22
|
+
|
|
23
|
+
# bun
|
|
24
|
+
bun add @temps-sdk/kv
|
|
25
|
+
|
|
26
|
+
# pnpm
|
|
27
|
+
pnpm add @temps-sdk/kv
|
|
28
|
+
|
|
29
|
+
# yarn
|
|
30
|
+
yarn add @temps-sdk/kv
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Quick Start
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
import { kv } from '@temps-sdk/kv';
|
|
37
|
+
|
|
38
|
+
await kv.set('user:123', { name: 'Alice', plan: 'pro' });
|
|
39
|
+
|
|
40
|
+
const user = await kv.get<{ name: string; plan: string }>('user:123');
|
|
41
|
+
// { name: 'Alice', plan: 'pro' }
|
|
42
|
+
|
|
43
|
+
await kv.del('user:123');
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
That's it. The `kv` singleton reads `TEMPS_API_URL` and `TEMPS_TOKEN` from your environment automatically.
|
|
47
|
+
|
|
48
|
+
## Configuration
|
|
49
|
+
|
|
50
|
+
### Environment Variables
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
TEMPS_API_URL=https://your-instance.temps.dev # Your Temps API URL
|
|
54
|
+
TEMPS_TOKEN=your-token # API key or deployment token
|
|
55
|
+
TEMPS_PROJECT_ID=42 # Required for API keys, optional for deployment tokens
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Explicit Configuration
|
|
59
|
+
|
|
60
|
+
```typescript
|
|
61
|
+
import { createClient } from '@temps-sdk/kv';
|
|
62
|
+
|
|
63
|
+
const kv = createClient({
|
|
64
|
+
apiUrl: 'https://your-instance.temps.dev',
|
|
65
|
+
token: 'your-token',
|
|
66
|
+
projectId: 42,
|
|
67
|
+
});
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
> **Deployment tokens** embed the project ID, so `projectId` is optional. **API keys** require `projectId` to be set explicitly.
|
|
71
|
+
|
|
72
|
+
## API Reference
|
|
73
|
+
|
|
74
|
+
### `get<T>(key): Promise<T | null>`
|
|
75
|
+
|
|
76
|
+
Retrieve a value by key. Returns `null` if the key does not exist.
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
const session = await kv.get<{ userId: string; expiresAt: number }>('session:abc');
|
|
80
|
+
|
|
81
|
+
if (session) {
|
|
82
|
+
console.log(session.userId);
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### `set(key, value, options?): Promise<'OK' | null>`
|
|
87
|
+
|
|
88
|
+
Store a JSON-serializable value. Returns `'OK'` on success, `null` if a conditional write failed.
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
// Simple set
|
|
92
|
+
await kv.set('config:theme', 'dark');
|
|
93
|
+
|
|
94
|
+
// Set with expiration (seconds)
|
|
95
|
+
await kv.set('cache:homepage', htmlContent, { ex: 300 });
|
|
96
|
+
|
|
97
|
+
// Set with expiration (milliseconds)
|
|
98
|
+
await kv.set('rate:user:123', 1, { px: 60000 });
|
|
99
|
+
|
|
100
|
+
// Only set if key does NOT exist (create-if-missing)
|
|
101
|
+
const result = await kv.set('lock:deploy', '1', { nx: true, ex: 30 });
|
|
102
|
+
if (result === null) {
|
|
103
|
+
console.log('Lock already held');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Only set if key already exists (update-if-exists)
|
|
107
|
+
await kv.set('user:123:status', 'active', { xx: true });
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
**Options:**
|
|
111
|
+
|
|
112
|
+
| Option | Type | Description |
|
|
113
|
+
|--------|------|-------------|
|
|
114
|
+
| `ex` | `number` | Expire after N seconds |
|
|
115
|
+
| `px` | `number` | Expire after N milliseconds |
|
|
116
|
+
| `nx` | `boolean` | Only set if key does **not** exist |
|
|
117
|
+
| `xx` | `boolean` | Only set if key **already** exists |
|
|
118
|
+
|
|
119
|
+
### `del(...keys): Promise<number>`
|
|
120
|
+
|
|
121
|
+
Delete one or more keys. Returns the number of keys that were removed.
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
const removed = await kv.del('temp:a', 'temp:b', 'temp:c');
|
|
125
|
+
console.log(`Removed ${removed} keys`);
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### `incr(key): Promise<number>`
|
|
129
|
+
|
|
130
|
+
Atomically increment a numeric value by 1. If the key does not exist, it is initialized to `0` before incrementing.
|
|
131
|
+
|
|
132
|
+
```typescript
|
|
133
|
+
const views = await kv.incr('page:views:/pricing');
|
|
134
|
+
console.log(`Page views: ${views}`);
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### `expire(key, seconds): Promise<number>`
|
|
138
|
+
|
|
139
|
+
Set a TTL on an existing key. Returns `1` if the timeout was set, `0` if the key does not exist.
|
|
140
|
+
|
|
141
|
+
```typescript
|
|
142
|
+
await kv.set('session:xyz', data);
|
|
143
|
+
await kv.expire('session:xyz', 3600); // Expire in 1 hour
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### `ttl(key): Promise<number>`
|
|
147
|
+
|
|
148
|
+
Get the remaining time-to-live of a key in seconds.
|
|
149
|
+
|
|
150
|
+
| Return value | Meaning |
|
|
151
|
+
|---|---|
|
|
152
|
+
| `>= 0` | Seconds remaining |
|
|
153
|
+
| `-1` | Key exists but has no expiration |
|
|
154
|
+
| `-2` | Key does not exist |
|
|
155
|
+
|
|
156
|
+
```typescript
|
|
157
|
+
const remaining = await kv.ttl('session:xyz');
|
|
158
|
+
|
|
159
|
+
if (remaining === -2) {
|
|
160
|
+
console.log('Session expired or never existed');
|
|
161
|
+
} else if (remaining === -1) {
|
|
162
|
+
console.log('Session has no expiration');
|
|
163
|
+
} else {
|
|
164
|
+
console.log(`Session expires in ${remaining}s`);
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
### `keys(pattern): Promise<string[]>`
|
|
169
|
+
|
|
170
|
+
Find all keys matching a glob-style pattern.
|
|
171
|
+
|
|
172
|
+
```typescript
|
|
173
|
+
const userKeys = await kv.keys('user:*');
|
|
174
|
+
// ['user:123', 'user:456', 'user:789']
|
|
175
|
+
|
|
176
|
+
const sessionKeys = await kv.keys('session:*');
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
> Use `keys` for debugging and administration. In production, prefer direct key access for performance.
|
|
180
|
+
|
|
181
|
+
## Usage Patterns
|
|
182
|
+
|
|
183
|
+
### Caching
|
|
184
|
+
|
|
185
|
+
```typescript
|
|
186
|
+
async function getProduct(id: string) {
|
|
187
|
+
const cached = await kv.get<Product>(`product:${id}`);
|
|
188
|
+
if (cached) return cached;
|
|
189
|
+
|
|
190
|
+
const product = await db.products.findById(id);
|
|
191
|
+
await kv.set(`product:${id}`, product, { ex: 600 }); // Cache for 10 minutes
|
|
192
|
+
return product;
|
|
193
|
+
}
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
### Rate Limiting
|
|
197
|
+
|
|
198
|
+
```typescript
|
|
199
|
+
async function checkRateLimit(userId: string): Promise<boolean> {
|
|
200
|
+
const key = `ratelimit:${userId}`;
|
|
201
|
+
const count = await kv.incr(key);
|
|
202
|
+
|
|
203
|
+
if (count === 1) {
|
|
204
|
+
await kv.expire(key, 60); // 60-second window
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
return count <= 100; // 100 requests per minute
|
|
208
|
+
}
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
### Distributed Locks
|
|
212
|
+
|
|
213
|
+
```typescript
|
|
214
|
+
async function withLock<T>(name: string, fn: () => Promise<T>): Promise<T | null> {
|
|
215
|
+
const acquired = await kv.set(`lock:${name}`, Date.now(), { nx: true, ex: 30 });
|
|
216
|
+
|
|
217
|
+
if (acquired === null) return null; // Lock held by another process
|
|
218
|
+
|
|
219
|
+
try {
|
|
220
|
+
return await fn();
|
|
221
|
+
} finally {
|
|
222
|
+
await kv.del(`lock:${name}`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
### Feature Flags
|
|
228
|
+
|
|
229
|
+
```typescript
|
|
230
|
+
await kv.set('feature:dark-mode', { enabled: true, rollout: 0.5 });
|
|
231
|
+
|
|
232
|
+
const flag = await kv.get<{ enabled: boolean; rollout: number }>('feature:dark-mode');
|
|
233
|
+
if (flag?.enabled && Math.random() < flag.rollout) {
|
|
234
|
+
// Show dark mode
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
## Multiple Clients
|
|
239
|
+
|
|
240
|
+
Create separate instances for different use cases:
|
|
241
|
+
|
|
242
|
+
```typescript
|
|
243
|
+
import { KV } from '@temps-sdk/kv';
|
|
244
|
+
|
|
245
|
+
const cache = new KV({ apiUrl: '...', token: '...' });
|
|
246
|
+
const sessions = new KV({ apiUrl: '...', token: '...' });
|
|
247
|
+
|
|
248
|
+
await cache.set('page:home', html, { ex: 300 });
|
|
249
|
+
await sessions.set('sess:abc', userData, { ex: 86400 });
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
## Error Handling
|
|
253
|
+
|
|
254
|
+
All errors are instances of `KVError` with structured details:
|
|
255
|
+
|
|
256
|
+
```typescript
|
|
257
|
+
import { kv, KVError } from '@temps-sdk/kv';
|
|
258
|
+
|
|
259
|
+
try {
|
|
260
|
+
await kv.get('my-key');
|
|
261
|
+
} catch (error) {
|
|
262
|
+
if (error instanceof KVError) {
|
|
263
|
+
console.error(error.message); // Human-readable message
|
|
264
|
+
console.error(error.code); // Error code (see table below)
|
|
265
|
+
console.error(error.status); // HTTP status code (if applicable)
|
|
266
|
+
console.error(error.title); // RFC 7807 problem title
|
|
267
|
+
console.error(error.detail); // RFC 7807 problem detail
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
**Error codes:**
|
|
273
|
+
|
|
274
|
+
| Code | Description |
|
|
275
|
+
|------|-------------|
|
|
276
|
+
| `MISSING_CONFIG` | Required environment variable or config option not set |
|
|
277
|
+
| `NETWORK_ERROR` | Failed to reach the Temps API |
|
|
278
|
+
| *HTTP status codes* | API-level errors with RFC 7807 Problem Details |
|
|
279
|
+
|
|
280
|
+
## TypeScript
|
|
281
|
+
|
|
282
|
+
Full type safety out of the box. Generic `get<T>()` returns correctly typed values:
|
|
283
|
+
|
|
284
|
+
```typescript
|
|
285
|
+
interface UserSession {
|
|
286
|
+
userId: string;
|
|
287
|
+
role: 'admin' | 'member';
|
|
288
|
+
expiresAt: number;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const session = await kv.get<UserSession>('session:abc');
|
|
292
|
+
// ^? UserSession | null
|
|
293
|
+
|
|
294
|
+
if (session) {
|
|
295
|
+
session.role; // 'admin' | 'member' -- fully typed
|
|
296
|
+
}
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
## Requirements
|
|
300
|
+
|
|
301
|
+
- Node.js 18+ or Bun
|
|
302
|
+
- A running Temps instance
|
|
303
|
+
|
|
304
|
+
## Related
|
|
305
|
+
|
|
306
|
+
- [`@temps-sdk/blob`](https://www.npmjs.com/package/@temps-sdk/blob) -- File storage
|
|
307
|
+
- [`@temps-sdk/react-analytics`](https://www.npmjs.com/package/@temps-sdk/react-analytics) -- React analytics, session replay, error tracking
|
|
308
|
+
- [`@temps-sdk/node-sdk`](https://www.npmjs.com/package/@temps-sdk/node-sdk) -- Full platform API client and server-side error tracking
|
|
309
|
+
|
|
310
|
+
## License
|
|
311
|
+
|
|
312
|
+
MIT
|