|
| 1 | +--- |
| 2 | +title: Key-Value Store |
| 3 | +--- |
| 4 | + |
| 5 | +CommandKit provides a built-in key-value store that offers simple, |
| 6 | +persistent storage using SQLite. It supports storing any |
| 7 | +JSON-serializable data types directly, including objects, arrays, |
| 8 | +dates, maps, sets, and more. |
| 9 | + |
| 10 | +## Basic usage |
| 11 | + |
| 12 | +The simplest way to use the key-value store is to create an instance |
| 13 | +and start storing data: |
| 14 | + |
| 15 | +```typescript |
| 16 | +import { KV } from 'commandkit/kv'; |
| 17 | + |
| 18 | +// Create a new KV store |
| 19 | +const kv = new KV('data.db'); |
| 20 | + |
| 21 | +// Store data directly |
| 22 | +kv.set('user:123', { name: 'John', age: 30 }); |
| 23 | +kv.set('counter', 42); |
| 24 | +kv.set('active', true); |
| 25 | + |
| 26 | +// Retrieve data |
| 27 | +const user = kv.get('user:123'); // { name: 'John', age: 30 } |
| 28 | +const counter = kv.get('counter'); // 42 |
| 29 | +``` |
| 30 | + |
| 31 | +## Configuration options |
| 32 | + |
| 33 | +You can customize the key-value store with various options: |
| 34 | + |
| 35 | +```typescript |
| 36 | +import { openKV } from 'commandkit/kv'; |
| 37 | + |
| 38 | +// Create with custom database file |
| 39 | +const kv = openKV('my-bot-data.db'); |
| 40 | + |
| 41 | +// In-memory store for testing |
| 42 | +const testKv = openKV(':memory:'); |
| 43 | + |
| 44 | +// Create with specific namespace |
| 45 | +const userKv = openKV('data.db', { |
| 46 | + namespace: 'users', |
| 47 | +}); |
| 48 | +``` |
| 49 | + |
| 50 | +## Supported data types |
| 51 | + |
| 52 | +The KV store supports storing and retrieving these data types: |
| 53 | + |
| 54 | +- **Primitives**: `string`, `number`, `boolean`, `bigint`, `null`, |
| 55 | + `undefined` |
| 56 | +- **Objects**: Plain objects, nested objects |
| 57 | +- **Arrays**: Any array of supported types |
| 58 | +- **Dates**: JavaScript Date objects |
| 59 | +- **Collections**: `Map`, `Set` |
| 60 | +- **Buffers**: Node.js Buffer objects |
| 61 | +- **Regular Expressions**: RegExp objects |
| 62 | +- **Functions**: Function objects (serialized as strings) |
| 63 | + |
| 64 | +```typescript |
| 65 | +// Store different data types |
| 66 | +kv.set('user', { name: 'John', preferences: { theme: 'dark' } }); |
| 67 | +kv.set('tags', ['javascript', 'typescript', 'discord']); |
| 68 | +kv.set('created_at', new Date()); |
| 69 | +kv.set( |
| 70 | + 'permissions', |
| 71 | + new Map([ |
| 72 | + ['admin', true], |
| 73 | + ['user', false], |
| 74 | + ]), |
| 75 | +); |
| 76 | +kv.set('unique_ids', new Set([1, 2, 3])); |
| 77 | +``` |
| 78 | + |
| 79 | +## Dot notation for nested access |
| 80 | + |
| 81 | +Access and modify nested properties using dot notation: |
| 82 | + |
| 83 | +```typescript |
| 84 | +// Store an object |
| 85 | +kv.set('user:123', { |
| 86 | + name: 'John Doe', |
| 87 | + settings: { |
| 88 | + theme: 'dark', |
| 89 | + notifications: { email: true, push: false }, |
| 90 | + }, |
| 91 | +}); |
| 92 | + |
| 93 | +// Access nested properties |
| 94 | +const theme = kv.get('user:123.settings.theme'); // 'dark' |
| 95 | +const emailNotifications = kv.get( |
| 96 | + 'user:123.settings.notifications.email', |
| 97 | +); // true |
| 98 | + |
| 99 | +// Set nested properties |
| 100 | +kv.set('user:123.settings.theme', 'light'); |
| 101 | +kv.set('user:123.settings.notifications.push', true); |
| 102 | +``` |
| 103 | + |
| 104 | +## Namespaces |
| 105 | + |
| 106 | +Organize your data into logical groups using namespaces: |
| 107 | + |
| 108 | +```typescript |
| 109 | +const kv = openKV('bot-data.db'); |
| 110 | + |
| 111 | +// Create namespace instances |
| 112 | +const userKv = kv.namespace('users'); |
| 113 | +const configKv = kv.namespace('config'); |
| 114 | +const guildKv = kv.namespace('guilds'); |
| 115 | + |
| 116 | +// Store data in different namespaces |
| 117 | +userKv.set('123', { name: 'John', level: 5 }); |
| 118 | +configKv.set('theme', 'dark'); |
| 119 | +guildKv.set('456', { name: 'My Server', premium: true }); |
| 120 | + |
| 121 | +// Same key in different namespaces |
| 122 | +userKv.set('settings', { theme: 'light' }); |
| 123 | +configKv.set('settings', { maintenance: false }); |
| 124 | +``` |
| 125 | + |
| 126 | +### Namespace operations |
| 127 | + |
| 128 | +Each namespace has its own isolated operations: |
| 129 | + |
| 130 | +```typescript |
| 131 | +// Check current namespace |
| 132 | +console.log(userKv.getCurrentNamespace()); // 'users' |
| 133 | + |
| 134 | +// List all namespaces |
| 135 | +const namespaces = kv.namespaces(); |
| 136 | +console.log('Available namespaces:', namespaces); |
| 137 | + |
| 138 | +// Namespace-specific counts and data |
| 139 | +console.log(`Users: ${userKv.count()}`); |
| 140 | +console.log('User keys:', userKv.keys()); |
| 141 | +console.log('All users:', userKv.all()); |
| 142 | +``` |
| 143 | + |
| 144 | +## Expiration support |
| 145 | + |
| 146 | +Set automatic expiration for temporary data: |
| 147 | + |
| 148 | +```typescript |
| 149 | +// Set data with expiration (1 hour) |
| 150 | +kv.setex( |
| 151 | + 'session:123', |
| 152 | + { userId: 123, token: 'abc123' }, |
| 153 | + 60 * 60 * 1000, |
| 154 | +); |
| 155 | + |
| 156 | +// Set expiration for existing keys |
| 157 | +kv.set('user:123', { name: 'John' }); |
| 158 | +kv.expire('user:123', 30 * 60 * 1000); // 30 minutes |
| 159 | + |
| 160 | +// Check time to live |
| 161 | +const ttl = kv.ttl('user:123'); |
| 162 | +if (ttl > 0) { |
| 163 | + console.log(`Expires in ${Math.floor(ttl / 1000)} seconds`); |
| 164 | +} |
| 165 | +``` |
| 166 | + |
| 167 | +## Transactions |
| 168 | + |
| 169 | +Execute multiple operations atomically: |
| 170 | + |
| 171 | +```typescript |
| 172 | +// Basic transaction |
| 173 | +kv.transaction(() => { |
| 174 | + kv.set('user:123', { balance: 100 }); |
| 175 | + kv.set('user:456', { balance: 200 }); |
| 176 | + // If any operation fails, all changes are rolled back |
| 177 | +}); |
| 178 | + |
| 179 | +// Async transactions |
| 180 | +await kv.transaction(async () => { |
| 181 | + const user = kv.get('user:123') || { balance: 0 }; |
| 182 | + user.balance += 50; |
| 183 | + kv.set('user:123', user); |
| 184 | + |
| 185 | + // Log the transaction |
| 186 | + kv.set(`transaction:${Date.now()}`, { |
| 187 | + type: 'deposit', |
| 188 | + amount: 50, |
| 189 | + timestamp: new Date(), |
| 190 | + }); |
| 191 | +}); |
| 192 | +``` |
| 193 | + |
| 194 | +## Bulk operations |
| 195 | + |
| 196 | +Work with multiple entries efficiently: |
| 197 | + |
| 198 | +```typescript |
| 199 | +// Get all data |
| 200 | +const allData = kv.all(); |
| 201 | +const keys = kv.keys(); |
| 202 | +const values = kv.values(); |
| 203 | +const count = kv.count(); |
| 204 | + |
| 205 | +// Iterate over entries |
| 206 | +for (const [key, value] of kv) { |
| 207 | + console.log(`${key}:`, value); |
| 208 | +} |
| 209 | + |
| 210 | +// Filter entries |
| 211 | +const userEntries = [...kv].filter(([key]) => |
| 212 | + key.startsWith('user:'), |
| 213 | +); |
| 214 | + |
| 215 | +// Check existence |
| 216 | +if (kv.has('user:123')) { |
| 217 | + console.log('User exists'); |
| 218 | +} |
| 219 | + |
| 220 | +// Delete data |
| 221 | +kv.delete('user:123'); |
| 222 | +kv.clear(); // Clear all data in current namespace |
| 223 | +``` |
| 224 | + |
| 225 | +## Resource management |
| 226 | + |
| 227 | +Use proper resource management to ensure database connections are |
| 228 | +closed: |
| 229 | + |
| 230 | +```typescript |
| 231 | +// Automatic cleanup with using statement |
| 232 | +{ |
| 233 | + using kv = openKV('data.db'); |
| 234 | + kv.set('key', 'value'); |
| 235 | + // kv is automatically closed when the block ends |
| 236 | +} |
| 237 | + |
| 238 | +// Manual cleanup |
| 239 | +const kv = openKV('data.db'); |
| 240 | +try { |
| 241 | + kv.set('key', 'value'); |
| 242 | +} finally { |
| 243 | + kv.close(); |
| 244 | +} |
| 245 | +``` |
0 commit comments