mxivideo/src/utils/cloudflareKV.example.ts

225 lines
6.4 KiB
TypeScript

/**
* Cloudflare KV Usage Examples
*
* This file demonstrates how to use the CloudflareKVClient utility class
*/
import { CloudflareKVClient, cloudflareKV } from './cloudflareKV'
// Example 1: Using the default instance
async function basicUsageExample() {
try {
// Store a simple string value
await cloudflareKV.put('user:123', 'John Doe')
console.log('✅ Stored user name')
// Store a JSON object
const userData = {
id: 123,
name: 'John Doe',
email: 'john@example.com',
preferences: {
theme: 'dark',
language: 'en'
}
}
await cloudflareKV.put('user:123:profile', userData)
console.log('✅ Stored user profile')
// Retrieve the data
const name = await cloudflareKV.get('user:123', false) // Don't parse as JSON
const profile = await cloudflareKV.get('user:123:profile') // Parse as JSON
console.log('Retrieved name:', name)
console.log('Retrieved profile:', profile)
// Check if a key exists
const exists = await cloudflareKV.exists('user:123')
console.log('User exists:', exists)
// List keys with prefix
const keys = await cloudflareKV.listKeys('user:')
console.log('User keys:', keys.result.keys)
} catch (error) {
console.error('❌ Error in basic usage example:', error)
}
}
// Example 2: Using a custom configuration
async function customConfigExample() {
const customKV = new CloudflareKVClient({
// You can override any configuration values
apiKey: 'your-custom-api-key',
// Other values will use defaults
})
try {
await customKV.put('custom:test', { message: 'Hello from custom config!' })
const result = await customKV.get('custom:test')
console.log('Custom config result:', result)
} catch (error) {
console.error('❌ Error in custom config example:', error)
}
}
// Example 3: Batch operations
async function batchOperationsExample() {
try {
// Store multiple values at once
const entries = [
{ key: 'batch:item1', value: { name: 'Item 1', price: 10.99 } },
{ key: 'batch:item2', value: { name: 'Item 2', price: 15.50 } },
{ key: 'batch:item3', value: { name: 'Item 3', price: 8.75 } }
]
const results = await cloudflareKV.putBatch(entries)
console.log('Batch put results:', results)
// Retrieve all batch items
for (const entry of entries) {
const item = await cloudflareKV.get(entry.key)
console.log(`Retrieved ${entry.key}:`, item)
}
} catch (error) {
console.error('❌ Error in batch operations example:', error)
}
}
// Example 4: Working with metadata
async function metadataExample() {
try {
const value = { content: 'Important data' }
const metadata = {
created_at: new Date().toISOString(),
created_by: 'user:123',
version: '1.0'
}
await cloudflareKV.put('data:important', value, metadata)
console.log('✅ Stored data with metadata')
// Note: To retrieve metadata, you'd need to use the Cloudflare API directly
// as the get method only returns the value, not metadata
} catch (error) {
console.error('❌ Error in metadata example:', error)
}
}
// Example 5: Error handling and edge cases
async function errorHandlingExample() {
try {
// Try to get a non-existent key
const nonExistent = await cloudflareKV.get('does-not-exist')
console.log('Non-existent key result:', nonExistent) // Should be null
// Store and then delete a key
await cloudflareKV.put('temp:data', 'temporary value')
console.log('✅ Stored temporary data')
const beforeDelete = await cloudflareKV.get('temp:data')
console.log('Before delete:', beforeDelete)
await cloudflareKV.delete('temp:data')
console.log('✅ Deleted temporary data')
const afterDelete = await cloudflareKV.get('temp:data')
console.log('After delete:', afterDelete) // Should be null
} catch (error) {
console.error('❌ Error in error handling example:', error)
}
}
// Example 6: Video template storage use case
async function videoTemplateStorageExample() {
try {
const templateData = {
id: 'template-001',
name: 'Modern Intro Template',
description: 'A sleek modern intro template with animations',
duration: 5000, // 5 seconds
assets: [
{ type: 'video', url: 'https://example.com/intro.mp4' },
{ type: 'audio', url: 'https://example.com/music.mp3' }
],
settings: {
resolution: '1920x1080',
fps: 30,
format: 'mp4'
},
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
}
// Store template
await cloudflareKV.put(`template:${templateData.id}`, templateData)
console.log('✅ Stored video template')
// Store template index for quick listing
const templateIndex = {
id: templateData.id,
name: templateData.name,
description: templateData.description,
thumbnail: 'https://example.com/thumbnail.jpg'
}
await cloudflareKV.put(`template:index:${templateData.id}`, templateIndex)
console.log('✅ Stored template index')
// Retrieve template
const retrievedTemplate = await cloudflareKV.get(`template:${templateData.id}`)
console.log('Retrieved template:', retrievedTemplate)
// List all templates
const templateKeys = await cloudflareKV.listKeys('template:index:', 100)
console.log('Template list:', templateKeys.result.keys)
} catch (error) {
console.error('❌ Error in video template storage example:', error)
}
}
// Run all examples
async function runAllExamples() {
console.log('🚀 Running Cloudflare KV Examples...\n')
console.log('1. Basic Usage Example:')
await basicUsageExample()
console.log('\n')
console.log('2. Custom Config Example:')
await customConfigExample()
console.log('\n')
console.log('3. Batch Operations Example:')
await batchOperationsExample()
console.log('\n')
console.log('4. Metadata Example:')
await metadataExample()
console.log('\n')
console.log('5. Error Handling Example:')
await errorHandlingExample()
console.log('\n')
console.log('6. Video Template Storage Example:')
await videoTemplateStorageExample()
console.log('\n')
console.log('✅ All examples completed!')
}
// Export individual examples for selective testing
export {
basicUsageExample,
customConfigExample,
batchOperationsExample,
metadataExample,
errorHandlingExample,
videoTemplateStorageExample,
runAllExamples
}