cloudkv-sdk
v0.0.4
Published
CloudKV SDK is a lightweight client library for interacting with the CloudKV high-performance key-value database. This SDK allows you to easily integrate CloudKV into your JavaScript applications, whether they're running in the browser or Node.js environm
Downloads
29
Readme
CloudKV SDK
CloudKV SDK is a lightweight client library for interacting with the CloudKV high-performance key-value database. This SDK allows you to easily integrate CloudKV into your JavaScript applications, whether they're running in the browser or Node.js environment.
What is CloudKV?
CloudKV is a high-performance key-value database designed specifically for environments with high concurrency. It combines the speed of in-memory databases with the reliability of persistent storage, offering an ideal solution for modern applications that require both performance and data integrity.
How CloudKV Works
CloudKV operates on a hybrid architecture that leverages:
- Memory-First Design: All data is stored in an optimized in-memory structure (memtable) for ultra-fast access
- Persistent Storage: Data is automatically persisted to disk through a Write-Ahead Log (WAL) to prevent data loss
- Sharding: Data is automatically distributed across multiple shards to enhance performance and scalability
- Granular Locking: Advanced lock management allows high concurrency without sacrificing data consistency
- Backpressure Control: Built-in mechanisms prevent system overload during traffic spikes
- Worker Threads: Operations are processed in parallel using worker threads for maximum throughput
What Makes CloudKV Different
CloudKV stands out from other key-value stores in several key areas:
- Optimized for Concurrency: Designed from the ground up to handle thousands of simultaneous operations with minimal lock contention
- Conflict Resolution: Built-in strategies for resolving conflicts in distributed environments
- Rich Data Structures: Native support for complex data types including hashes, lists, and sets
- Expiration Management: Sophisticated TTL and expiration handling
- Operational Simplicity: No complex configuration required - works out of the box
- Cross-Platform: Accessible from any device or platform that can make HTTP requests
CloudKV is ideal for:
- Session storage
- Caching layers
- Real-time applications
- IoT data collection
- High-traffic web applications
- Distributed systems
- Microservices architectures
Features
- Cross-platform: Works in both browser and Node.js environments
- Complete API: Support for all CloudKV operations
- Data structures: Support for key-value pairs, hashes, lists, and sets
- Promise-based: Modern, asynchronous API with promises
Installation
Browser
<script src="https://cdn.example.com/cloudkv-sdk.min.js"></script>Node.js
npm install cloudkv-sdkAPI Keys
CloudKV uses a prefix-based API key system to differentiate between browser and server environments:
- Public Keys (
pk_): For use in browser environments. These keys are restricted to the domain they're registered with. - Secret Keys (
sk_): For use in server environments. These keys should never be exposed in client-side code. - Development Keys (
pk_dev_,sk_dev_): Special keys for local development environments.
Security Notes
- Always use the appropriate key type for your environment
- Never expose your secret keys (
sk_) in client-side code - Public keys (
pk_) are domain-restricted and only work on registered domains - Development keys work only on localhost environments
Usage
Initializing the SDK
// Browser (using your public key)
const cloudKV = new CloudKV({
apikey: 'pk_your_public_key'
});
// Node.js (using your secret key)
const CloudKV = require('cloudkv-sdk');
const cloudKV = new CloudKV({
apikey: 'sk_your_secret_key'
});
// Local development (using your development key)
const devCloudKV = new CloudKV({
apikey: 'dk_your_development_key'
});Basic Key-Value Operations
Setting a Value
// Set a simple string value
cloudKV.set('greeting', 'Hello, World!')
.then(success => console.log(`Operation successful: ${success}`))
.catch(error => console.error(`Error: ${error.message}`));
// Set a JSON object
cloudKV.set('user:1001', {
name: 'Maria Silva',
email: '[email protected]',
age: 32
})
.then(success => console.log(`User saved: ${success}`))
.catch(error => console.error(`Error: ${error.message}`));Getting a Value
// Get a value
cloudKV.get('greeting')
.then(value => console.log(`Value: ${value}`))
.catch(error => console.error(`Error: ${error.message}`));
// Get a JSON object
cloudKV.get('user:1001')
.then(user => {
if (user) {
console.log(`User: ${user.name}, Email: ${user.email}`);
} else {
console.log('User not found');
}
})
.catch(error => console.error(`Error: ${error.message}`));Deleting a Value
cloudKV.del('greeting')
.then(success => console.log(`Value deleted: ${success}`))
.catch(error => console.error(`Error: ${error.message}`));Expiration & TTL
Setting Expiration
// Make key expire after 60 seconds
cloudKV.expire('session:token', 60)
.then(success => console.log(`Expiration set: ${success}`))
.catch(error => console.error(`Error: ${error.message}`));Getting TTL (Time-To-Live)
cloudKV.ttl('session:token')
.then(seconds => {
if (seconds > 0) {
console.log(`Key will expire in ${seconds} seconds`);
} else if (seconds === -1) {
console.log('Key has no expiration');
} else if (seconds === -2) {
console.log('Key does not exist');
}
})
.catch(error => console.error(`Error: ${error.message}`));Hash Operations
Hashes are maps of field-value pairs, ideal for storing objects with multiple attributes.
Setting Hash Fields
// Set a single field
cloudKV.hset('product:1001', 'name', 'Smartphone XYZ')
.then(fieldsCount => console.log(`Fields added/updated: ${fieldsCount}`))
.catch(error => console.error(`Error: ${error.message}`));
// Set multiple fields at once (helper method)
cloudKV.hmset('product:1001', {
'price': 999.99,
'stock': 42,
'category': 'electronics'
})
.then(fieldsCount => console.log(`Fields added/updated: ${fieldsCount}`))
.catch(error => console.error(`Error: ${error.message}`));Getting Hash Fields
// Get a single field
cloudKV.hget('product:1001', 'name')
.then(value => console.log(`Product name: ${value}`))
.catch(error => console.error(`Error: ${error.message}`));
// Get all fields
cloudKV.hgetall('product:1001')
.then(product => {
console.log(`Product details:`, product);
// Example output: { name: 'Smartphone XYZ', price: 999.99, stock: 42, category: 'electronics' }
})
.catch(error => console.error(`Error: ${error.message}`));Deleting Hash Fields
cloudKV.hdel('product:1001', 'category')
.then(success => console.log(`Field deleted: ${success}`))
.catch(error => console.error(`Error: ${error.message}`));List Operations
Lists are ordered collections of values, useful for queues, logs, etc.
Adding Elements to a List
// Add elements to the beginning of the list
cloudKV.lpush('recent:logins', 'user:1001')
.then(listLength => console.log(`New list length: ${listLength}`))
.catch(error => console.error(`Error: ${error.message}`));
// Add multiple elements to the end of the list
cloudKV.rpush('recent:logins', 'user:1002', 'user:1003', 'user:1004')
.then(listLength => console.log(`New list length: ${listLength}`))
.catch(error => console.error(`Error: ${error.message}`));Getting Elements from a List
// Get a range of elements (start and end indexes)
cloudKV.lrange('recent:logins', 0, 2)
.then(elements => console.log(`Recent logins: ${elements.join(', ')}`))
.catch(error => console.error(`Error: ${error.message}`));
// Get all elements
cloudKV.lrange('recent:logins', 0, -1)
.then(elements => console.log(`All logins: ${elements.join(', ')}`))
.catch(error => console.error(`Error: ${error.message}`));Removing and Returning Elements
// Remove and return the first element (useful for queues)
cloudKV.lpop('recent:logins')
.then(element => console.log(`Removed first element: ${element}`))
.catch(error => console.error(`Error: ${error.message}`));
// Remove and return the last element
cloudKV.rpop('recent:logins')
.then(element => console.log(`Removed last element: ${element}`))
.catch(error => console.error(`Error: ${error.message}`));Set Operations
Sets are unordered collections of unique values.
Adding Elements to a Set
// Add one or more elements to a set
cloudKV.sadd('user:1001:permissions', 'read', 'write', 'delete')
.then(added => console.log(`Added ${added} new elements`))
.catch(error => console.error(`Error: ${error.message}`));Checking Set Membership
cloudKV.sismember('user:1001:permissions', 'admin')
.then(isMember => console.log(`Is member: ${isMember}`))
.catch(error => console.error(`Error: ${error.message}`));Getting All Set Members
cloudKV.smembers('user:1001:permissions')
.then(members => console.log(`Permissions: ${members.join(', ')}`))
.catch(error => console.error(`Error: ${error.message}`));Removing Set Members
cloudKV.srem('user:1001:permissions', 'delete')
.then(success => console.log(`Removed successfully: ${success}`))
.catch(error => console.error(`Error: ${error.message}`));Error Handling
All methods return promises, so you can use try/catch with async/await:
async function processUser(userId) {
try {
const user = await cloudKV.get(`user:${userId}`);
if (!user) {
throw new Error('User not found');
}
// Update last access time
user.lastAccess = new Date().toISOString();
await cloudKV.set(`user:${userId}`, user);
// Get permissions
const permissions = await cloudKV.smembers(`user:${userId}:permissions`);
return {
user,
permissions
};
} catch (error) {
console.error(`Error processing user ${userId}: ${error.message}`);
throw error;
}
}Development Environment
When working in a local development environment:
- Use development keys (
pk_dev_orsk_dev_) that will work with localhost - Development keys are automatically validated when running on localhost, 127.0.0.1, or *.local domains
- Your application will seamlessly transition between development and production by simply changing the API key
Example for local development:
// Detect environment and use appropriate key
const apiKey = window.location.hostname === 'localhost' || window.location.hostname.match(/^127\.0\.0\.\d+$/)
? 'dk_your_development_key'
: 'pk_your_public_key';
const cloudKV = new CloudKV({ apikey: apiKey });License
MIT
Support
For issues, feature requests, or questions, please contact [email protected] or open an issue in our GitHub repository.
