wick.db
v2.0.3
Published
A powerful, easy-to-use, and feature-rich SQLite-based key-value database for Node.js, Built with TypeScript.
Maintainers
Readme
WickDB
WickDB is a powerful, easy-to-use, and feature-rich SQLite-based key-value database for Node.js, written in TypeScript. Developed by Wick Studio, WickDB offers seamless data management with minimal setup, making it the perfect choice for developers looking to integrate a lightweight database into their applications.
📚 Table of Contents
- Introduction
- Features
- Installation
- Compatibility
- Quick Start
- Configuration Options
- API Reference
- Events
- Examples
- Best Practices
- Performance
- Security
- Contributing
- License
- Connect with Us
🌟 Introduction
WickDB is a lightweight yet powerful key-value store built on top of SQLite, designed for Node.js applications. It offers an intuitive API, making it easy to store and retrieve data without the overhead of setting up a full-fledged database. Whether you're building a small project or a large-scale application, WickDB provides the flexibility and performance you need.
🌟 Features
- Simple API: Effortless methods for common database operations.
- Advanced Operations: Supports array manipulation, math operations, data expiration (TTL), and nested property management.
- Bulk Operations: Efficient methods for setting and deleting multiple entries at once.
- Event Emitter: Listen to database events for reactive programming.
- TypeScript Support: Written in TypeScript with comprehensive type definitions.
- Lightweight: Minimal dependencies and a small footprint.
- Persistent Storage: Data is stored locally using SQLite, ensuring persistence across restarts.
- Customizable Logging: Multiple log levels to suit your debugging and monitoring needs.
- Secure: Handles data serialization and deserialization securely.
- Performance Optimized: Efficient data handling with in-memory caching for high-speed operations.
- Flexible Configuration: Customize database paths, table names, and more.
- Comprehensive Documentation: Clear and detailed documentation to get you started quickly.
🛠 Installation
Install WickDB via NPM:
npm install wick.db better-sqlite3Or using Yarn:
yarn add wick.db better-sqlite3⚙️ Compatibility
WickDB is compatible with the following Node.js versions:
- Node.js v16
- Node.js v18
- Node.js v20
Ensure you are using one of these supported versions to guarantee optimal performance and compatibility.
⚡ Quick Start
import { WickDB } from 'wick.db';
const db = new WickDB({ logLevel: 'info' });
// Set a value
db.set('username', 'Wick');
// Get a value
const username = db.get('username');
console.log('Username:', username); // Output: Username: Wick
// Delete a value
db.delete('username');
// Perform math operations
db.set('score', 10);
db.math('score', 'add', 5); // score is now 15
console.log('Score:', db.get('score')); // Output: Score: 15
// Use shorthand math methods
db.add('score', 5); // score is now 20
db.subtract('score', 10); // score is now 10
console.log('Updated Score:', db.get('score')); // Output: Updated Score: 10
// Work with arrays
db.set('items', ['apple']);
db.push('items', 'banana'); // items: ['apple', 'banana']
db.pull('items', 'apple'); // items: ['banana']
console.log('Items:', db.get('items')); // Output: Items: ['banana']
// Manage nested properties
db.set('user', { name: 'Wick' });
db.setProp('user', 'age', 30);
const age = db.getProp('user', 'age');
console.log('User Age:', age); // Output: User Age: 30
// Bulk operations
db.bulkSet([
{ key: 'bulk1', value: 'value1' },
{ key: 'bulk2', value: 'value2' },
]);
db.bulkDelete(['bulk1', 'bulk2']);
// Use event listeners
db.on('set', (key, value) => {
console.log(`Key "${key}" was set to`, value);
});
db.set('eventKey', 'eventValue'); // Triggers the 'set' event
// Handle data expiration (TTL)
db.set('tempKey', 'tempValue', 5000); // Expires in 5 seconds
// Retrieve keys starting with a prefix
db.set('user_1', 'Wick');
db.set('user_2', 'Studio');
const users = db.startsWith('user_');
console.log('Users:', users);
// Clear the database
db.clear();🛠 Configuration Options
When initializing WickDB, you can provide an optional configuration object:
const db = new WickDB({
dbPath: './data/my-database.db', // Default: '.wick.db'
logLevel: 'debug', // Default: 'info'
tableName: 'my_table', // Default: 'data'
});dbPath: The file path for the SQLite database.logLevel: Sets the logging level. Options are'debug','info','warn','error','none'.tableName: Sets a custom table name for data storage.cacheEnabled: (Optional) Enables or disables in-memory caching. Default istrue.encryption: (Optional) Enables encryption for the database. Requires additional setup.timeout: (Optional) Sets the timeout for database operations in milliseconds. Default is5000.
📖 API Reference
set(key: string, value: any, ttl?: number): void
Sets a value for a given key. Optionally, you can provide a TTL (time-to-live) in milliseconds.
Parameters:
key: The key under which the value will be stored.value: The value to store. Can be any serializable data.ttl(optional): Time in milliseconds after which the key expires.
Example:
db.set('session_token', 'abc123', 60000); // Expires in 1 minuteget(key: string): any
Retrieves the value associated with the given key. Returns null if the key doesn't exist or has expired.
Parameters:
key: The key to retrieve.
Example:
const token = db.get('session_token');has(key: string): boolean
Checks if a key exists in the database.
Parameters:
key: The key to check.
Example:
if (db.has('user_id')) {
// Do something
}delete(key: string): void
Deletes the key-value pair from the database.
Parameters:
key: The key to delete.
Example:
db.delete('tempKey');all(): DataRow[]
Retrieves all key-value pairs from the database.
Returns:
- An array of
DataRowobjects containingkey,value, and optionalttl.
Example:
const allData = db.all();clear(): void
Clears all data from the database.
Example:
db.clear();math(key: string, operator: MathOperator, value: number): void
Performs a mathematical operation on a stored number.
Parameters:
key: The key whose value to operate on.operator: The operation to perform ('add','subtract','multiply','divide').value: The number to use in the operation.
Example:
db.math('balance', 'subtract', 50);add(key: string, value: number): void
Adds a number to a stored number. Shorthand for math(key, 'add', value).
Parameters:
key: The key of the number.value: The number to add.
Example:
db.add('score', 10);subtract(key: string, value: number): void
Subtracts a number from a stored number. Shorthand for math(key, 'subtract', value).
Parameters:
key: The key of the number.value: The number to subtract.
Example:
db.subtract('score', 5);push(key: string, element: any): void
Appends an element to an array stored in the database. If the key doesn't exist, it creates a new array.
Parameters:
key: The key of the array.element: The element to append.
Example:
db.push('favorite_fruits', 'apple');pull(key: string, element: any): void
Removes an element from an array stored in the database.
Parameters:
key: The key of the array.element: The element to remove.
Example:
db.pull('favorite_fruits', 'banana');setProp(key: string, propPath: string, value: any): void
Sets a property of an object stored in the database using dot notation.
Parameters:
key: The key of the object.propPath: The dot-notated path of the property (e.g.,'address.city').value: The value to set.
Example:
db.setProp('user', 'address.city', 'New York');getProp(key: string, propPath: string): any
Gets a property of an object stored in the database using dot notation.
Parameters:
key: The key of the object.propPath: The dot-notated path of the property.
Example:
const city = db.getProp('user', 'address.city');bulkSet(entries: { key: string; value: any; ttl?: number }[]): void
Sets multiple key-value pairs in the database efficiently.
Parameters:
entries: An array of objects containingkey,value, and optionalttl.
Example:
db.bulkSet([
{ key: 'item1', value: 'value1' },
{ key: 'item2', value: 'value2', ttl: 3000 },
]);bulkDelete(keys: string[]): void
Deletes multiple keys from the database efficiently.
Parameters:
keys: An array of keys to delete.
Example:
db.bulkDelete(['item1', 'item2']);startsWith(prefix: string): DataRow[]
Retrieves all key-value pairs where the key starts with the specified prefix.
Parameters:
prefix: The prefix to search for.
Example:
const users = db.startsWith('user_');🔔 Events
WickDB extends Node.js's EventEmitter class, allowing you to listen for database events.
Supported Events:
'set': Emitted when a key is set.'delete': Emitted when a key is deleted.'clear': Emitted when the database is cleared.'expire': Emitted when a key expires.
Example:
db.on('set', (key, value) => {
console.log(`Key "${key}" was set to`, value);
});
db.on('delete', (key) => {
console.log(`Key "${key}" was deleted.`);
});
db.on('clear', () => {
console.log('Database was cleared.');
});
db.on('expire', (key) => {
console.log(`Key "${key}" has expired.`);
});📝 Examples
Basic Usage
import { WickDB } from 'wick.db';
const db = new WickDB();
// Storing data
db.set('user:1', { name: 'Wick', age: 30 });
// Retrieving data
const user = db.get('user:1');
console.log(user.name); // Output: Wick
// Checking existence
if (db.has('user:1')) {
console.log('User exists');
}
// Deleting data
db.delete('user:1');Advanced Operations
Nested Properties
// Setting nested properties
db.set('settings', {});
db.setProp('settings', 'theme.color', 'dark');
db.setProp('settings', 'notifications.email', true);
// Getting nested properties
const themeColor = db.getProp('settings', 'theme.color');
console.log('Theme Color:', themeColor); // Output: Theme Color: darkBulk Operations
// Bulk setting data
db.bulkSet([
{ key: 'product:1', value: { name: 'Laptop', price: 999 } },
{ key: 'product:2', value: { name: 'Phone', price: 499 } },
]);
// Bulk deleting data
db.bulkDelete(['product:1', 'product:2']);Math Operations
// Incrementing a value
db.set('counter', 10);
db.add('counter', 5); // counter is now 15
db.subtract('counter', 3); // counter is now 12
console.log('Counter:', db.get('counter')); // Output: Counter: 12Integrating with a Discord Bot
Here's how you might integrate WickDB into a Discord bot using discord.js:
const { Client, GatewayIntentBits, EmbedBuilder } = require('discord.js');
const { WickDB } = require('wick.db');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
const db = new WickDB();
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
if (message.content.startsWith('!set')) {
const args = message.content.split(' ');
const key = args[1];
const value = args.slice(2).join(' ');
db.set(`${message.author.id}_${key}`, value);
message.channel.send(`Set ${key} to ${value}.`);
}
if (message.content.startsWith('!get')) {
const args = message.content.split(' ');
const key = args[1];
const value = db.get(`${message.author.id}_${key}`);
message.channel.send(`Value for ${key}: ${value || 'Not found'}`);
}
if (message.content === '!leaderboard') {
const allData = db.all();
const users = allData.filter((entry) => entry.key.startsWith('points_'));
const embed = new EmbedBuilder().setTitle('Leaderboard');
for (const entry of users) {
const userId = entry.key.replace('points_', '');
const user = await client.users.fetch(userId).catch(() => null);
if (user) {
embed.addFields({ name: user.username, value: `${entry.value} points`, inline: true });
}
}
message.channel.send({ embeds: [embed] });
}
});
client.login('YOUR_DISCORD_BOT_TOKEN');🚀 Performance
WickDB is optimized for high-speed operations with efficient data handling and in-memory caching. It leverages SQLite's performance benefits, ensuring rapid read and write operations even with large datasets. Bulk operations are particularly optimized to reduce latency and improve throughput.
Key Performance Features:
- In-Memory Caching: Accelerates data retrieval and manipulation.
- Asynchronous Operations: Ensures non-blocking database interactions.
- Optimized Queries: Minimizes database access times with efficient querying mechanisms.
🔒 Security
Security is paramount when handling data. WickDB ensures secure data serialization and deserialization, preventing common vulnerabilities such as injection attacks. Additionally, optional encryption can be enabled to protect sensitive data at rest.
Security Features:
- Data Validation: Ensures only valid and expected data is stored.
- Optional Encryption: Protects data using industry-standard encryption algorithms.
- Access Control: Manage and restrict access to the database as needed.
- Regular Updates: Stay protected with ongoing security updates and patches.
Best Practices:
- Encrypt Sensitive Data: Use the
encryptionconfiguration option for sensitive information. - Validate Inputs: Always validate and sanitize data before storing.
- Limit Access: Restrict database access to authorized components or services.
- Regular Backups: Maintain secure backups to prevent data loss.
💡 Best Practices
- Error Handling: Always wrap database operations in try-catch blocks to handle potential errors.
- Data Validation: Validate data before storing to prevent issues with serialization/deserialization.
- Performance: Utilize bulk operations and in-memory caching for high-frequency operations.
- Backup: Regularly back up your database file, especially if data integrity is critical.
- Security: Ensure sensitive data is encrypted if necessary, and manage access appropriately.
- Modular Design: Structure your application to separate database logic from business logic for maintainability.
- Logging: Use appropriate log levels to monitor your application without overwhelming your logs.
- Stay Updated: Keep WickDB and its dependencies updated to benefit from the latest features and security patches.
🤝 Contributing
Contributions are welcome! If you'd like to contribute to WickDB, please follow these steps:
- Fork the Repository: Click the Fork button at the top right of the repository page.
- Clone Your Fork:
git clone https://github.com/your-username/wick.db.git - Create a New Branch:
git checkout -b feature/your-feature-name - Make Your Changes: Implement your feature or fix.
- Commit Your Changes:
git commit -am 'Add a new feature' - Push to the Branch:
git push origin feature/your-feature-name - Open a Pull Request: Go to the original repository and click on "Compare & pull request".
Please ensure your code follows the project's coding standards and passes all tests. For major changes, open an issue first to discuss what you'd like to change.
Guidelines:
- Code Quality: Write clean, readable, and maintainable code.
- Documentation: Update documentation as necessary to reflect your changes.
- Testing: Include tests for new features or bug fixes.
- Respect: Be respectful and considerate in all interactions.
📄 License
WickDB is released under the MIT License.
🌐 Connect with Us
- Discord: Join our community
- GitHub: Visit our repository
- Website: Wick Studio
- Twitter: @WickStudio
- YouTube: Wick Studio Channel
© 2025 Wick Studio
