webcake-data
v1.0.10
Published
A modern JavaScript/TypeScript client library for WebCake database operations with MongoDB-like query interface
Downloads
252
Maintainers
Readme
WebCake Data
A modern JavaScript/TypeScript client library for WebCake database operations with MongoDB-like query interface.
Features
- 🚀 Modern ES6+ Module Support - Works with both Node.js and browsers
- 🔍 MongoDB-like Query Interface - Familiar query syntax for easy adoption
- 🎯 TypeScript Support - Full TypeScript definitions included
- 🌐 Browser & Node.js Compatible - Works everywhere JavaScript runs
- 📦 Zero Dependencies - Lightweight with no external dependencies
- 🔗 Fluent API - Chainable query builder for complex operations
- ⚡ Minified Builds - Optimized and compressed for production use
Installation
npm install webcake-dataQuick Start
ES6 Modules
import { DBConnection } from 'webcake-data';
// Initialize connection
const db = new DBConnection({
// baseURL/siteId/token are preconfigured on WebCake-hosted sites;
// override only if you use a custom backend. Headers still need to be set.
baseURL: 'https://api.webcake.com/api/v1',
siteId: 'your-site-id',
token: 'your-auth-token',
headers: {
'x-cms-api-key': 'your-api-key' // For API permission checking
}
});
// Create a model
const User = db.model('users');
// Create a user
const user = await User.create({
name: 'John Doe',
email: '[email protected]',
age: 30,
active: true
});
// Find users
const users = await User.find({ active: true }).exec();CommonJS (Node.js)
const { DBConnection } = require('webcake-data');Browser (Global)
Using CDN (Unpkg or JSDelivr):
<!-- Minified version (recommended for production) -->
<script src="https://unpkg.com/webcake-data@latest/dist/webcake-data.umd.min.js"></script>
<script>
const db = new WebCakeData.DBConnection({
baseURL: '/api/v1',
siteId: 'your-site-id',
headers: {
'x-cms-api-key': 'your-api-key' // For API permission checking
}
});
</script>Using JSDelivr:
<script src="https://cdn.jsdelivr.net/npm/webcake-data@latest/dist/webcake-data.umd.min.js"></script>API Reference
DBConnection
Main connection class for database operations.
Constructor
new DBConnection(config)Parameters:
config.baseURL(string, optional): API base URLconfig.domain(string, optional): Domain base URL (overrides default relative path if provided)config.siteId(string, optional): Site ID (auto-detected from DOM if not provided)config.token(string, optional): Authentication tokenconfig.headers(object, optional): Additional headersconfig.headers['x-cms-api-key'](string, optional): API key for permission checking
Automatic Header Injection:
The library automatically monitors window.store_post and window.store_product. If present, it injects x-article-id and x-product-id headers respectively.
Example:
const db = new DBConnection({
baseURL: 'https://api.webcake.com/api/v1', // Optional: defaults to /api/v1
domain: 'https://api.webcake.com', // Optional: Base domain to prepend to baseURL
siteId: 'your-site-id',
token: 'your-auth-token',
headers: {
'x-cms-api-key': 'your-api-key' // For API permission checking
}
});
// Automatic Header Injection:
// If window.store_post or window.store_product are present,
// the library will automatically inject 'x-article-id' and 'x-product-id' headers.Methods
model(collectionName)- Create a model for a collectioninsertOne(tableName, fields)- Insert a single recordinsertMany(tableName, records)- Insert multiple recordsquery(tableName, queryParams)- Query recordsupdateById(tableName, id, fields)- Update record by IDupdateOne(tableName, filters, fields)- Update one recordupdateMany(tableName, filters, fields)- Update multiple recordsdeleteById(tableName, id)- Delete record by IDdeleteOne(tableName, filters)- Delete one recorddeleteMany(tableName, filters)- Delete multiple recordscount(tableName, filters)- Count recordsexists(tableName, filters)- Check if records exist
DBModel
Model class for collection operations.
Methods
create(data)- Create a new documentinsertMany(dataArray)- Create multiple documentsfind(filters)- Find documents (returns QueryBuilder)findOne(filters, options)- Find one document with optional select/sort/populatefindById(id, options)- Find document by ID with optional select/sort/populateupdateOne(filters, updateData)- Update one documentfindByIdAndUpdate(id, updateData, options)- Update document by IDfindOneAndUpdate(filters, updateData)- Find and update one documentupdateMany(filters, updateData)- Update multiple documentsdeleteOne(filters)- Delete one documentfindByIdAndDelete(id)- Delete document by IDfindOneAndDelete(filters)- Find and delete one documentdeleteMany(filters)- Delete multiple documentscountDocuments(filters)- Count documentsexists(filters)- Check if documents exist
findOne/findById options:
select(string | string[]): Fields to returnsort(object): Sort order applied before taking the first recordpopulate(object | object[]): Populate configuration(s) identical toQueryBuilder.populate()
QueryBuilder
Fluent query builder for complex database queries.
Methods
where(field, operator, value)- Add filter condition (supports: where(obj), where(field, value), or where(field, operator, value))eq(field, value)- Equality filtergt(field, value)- Greater than filtergte(field, value)- Greater than or equal filterlt(field, value)- Less than filterlte(field, value)- Less than or equal filterin(field, values)- In array filternin(field, values)- Not in array filterne(field, value)- Not equal filterbetween(field, value1, value2)- Between values filterlike(field, pattern)- Pattern matching filtersort(sortObj)- Sort resultslimit(n)- Limit number of resultsskip(n)- Skip number of resultsselect(fields)- Select specific fieldspopulate(config)- Populate related dataexec()- Execute query
Usage Examples
Basic CRUD Operations
import { DBConnection } from 'webcake-data';
const db = new DBConnection({
baseURL: 'https://api.webcake.com/api/v1',
siteId: 'your-site-id',
token: 'your-auth-token',
headers: {
'x-cms-api-key': 'your-api-key' // For API permission checking
}
});
const User = db.model('users');
// Create
const user = await User.create({
name: 'John Doe',
email: '[email protected]',
age: 30,
active: true
});
// Read
const users = await User.find({ active: true }).exec();
const user = await User.findOne(
{ email: '[email protected]' },
{
select: ['id', 'name', 'email'],
populate: {
field: 'profile',
table: 'profiles',
referenceField: 'user_id',
select: 'avatar bio'
}
}
);
const userById = await User.findById('user-id', {
select: 'id name email',
sort: { created_at: -1 }
});
// Update
await User.updateOne(
{ email: '[email protected]' },
{ age: 31, active: false }
);
await User.findByIdAndUpdate('user-id', { age: 32 }, { new: true });
// Delete
await User.deleteOne({ email: '[email protected]' });
await User.findByIdAndDelete('user-id');Advanced Queries
// Using where with object
const results1 = await User.find()
.where({ active: true, age: { $gte: 25 } })
.exec();
// Complex query with multiple conditions
const results = await User.find()
.where('age').gte(25).lte(40)
.where('active', true)
.in('name', ['John', 'Jane', 'Bob'])
.like('email', '%@example.com')
.sort({ age: -1, name: 1 })
.limit(20)
.skip(10)
.select('name email age')
.exec();
// Population (joins) with object-based where and sort
const usersWithPosts = await User.find()
.populate({
field: 'posts',
table: 'posts',
referenceField: 'user_id',
select: 'title content',
where: { published: true },
sort: { created_at: -1 },
limit: 5
})
.exec();
// Count and exists
const activeUserCount = await User.countDocuments({ active: true });
const userExists = await User.exists({ email: '[email protected]' });Batch Operations
// Insert multiple records
await User.insertMany([
{ name: 'Jane', email: '[email protected]', age: 25, active: true },
{ name: 'Bob', email: '[email protected]', age: 35, active: false }
]);
// Update multiple records
await User.updateMany({ active: false }, { active: true });
// Delete multiple records
await User.deleteMany({ active: false });Error Handling
try {
const user = await User.create({
name: 'John Doe',
email: '[email protected]'
});
} catch (error) {
console.error('Failed to create user:', error.message);
}TypeScript Support
The library includes full TypeScript definitions:
import { DBConnection, DBModel, QueryBuilder } from 'webcake-data';
interface User {
id: string;
name: string;
email: string;
age: number;
active: boolean;
}
const db = new DBConnection({
baseURL: 'https://api.webcake.com/api/v1',
siteId: 'your-site-id',
headers: {
'x-cms-api-key': 'your-api-key' // For API permission checking
}
});
const UserModel: DBModel = db.model<User>('users');Browser Integration
The library automatically detects the site ID from DOM attributes:
<html x:id="your-site-id" x:env="production">
<!-- Your content -->
</html>Or you can provide it explicitly:
const db = new DBConnection({
siteId: 'your-site-id'
});Development
Building the Library
The library uses Rollup for bundling and minification. Build scripts are available:
# Build minified and unminified versions for all formats
npm run build
# Production build with optimizations
npm run build:prodBuild outputs are generated in the dist/ directory:
webcake-data.esm.min.js- ES Module (minified, ~7.4KB)webcake-data.umd.min.js- UMD format (minified, ~7.6KB) - for browserswebcake-data.esm.js- ES Module (unminified)webcake-data.umd.js- UMD format (unminified)
File Sizes
The minified builds are optimized for production use:
- ESM Minified: ~7.4KB
- UMD Minified: ~7.6KB (includes browser global export)
Minification Details
The library is minified using Terser with the following optimizations:
- Variable name mangling
- Dead code elimination
- Whitespace and comment removal
- Property access optimization
- 2-pass compression for maximum size reduction
Contributing
To contribute to the library:
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Make your changes and add tests
- Run the build:
npm run build - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT License - see LICENSE file for details.
Support
For support, please open an issue on GitHub.
AI Helper Prompt
Users can copy this prompt into ChatGPT, Gemini, or any assistant to get high-quality help with WebCake Data. Share it together with the raw code bundle (https://raw.githubusercontent.com/vuluu2k/webcake-data/main/repomix-output.txt) so the AI can read the entire library context:
You are a senior engineer specializing in the WebCake Data JavaScript library (DBConnection, DBModel, QueryBuilder). Read the full repo context from https://raw.githubusercontent.com/vuluu2k/webcake-data/main/repomix-output.txt, then:
1. Clarify requirements you need (collection names, filters, select/populate needs, expected return shape, environment constraints).
2. Produce a brief plan describing which WebCake Data APIs to use and why.
3. Write idiomatic async/await code that follows the official API (DBConnection auto headers, DBModel.findOne/findById options, QueryBuilder chaining).
4. Explain key lines (e.g., why a populate is needed, how limit/skip behave, error-handling expectations).
5. Call out assumptions and note how to adapt/tests to run.
Rules:
- Use only documented public APIs; no private internals or speculative features.
- Keep snippets self-contained, production-ready, and aligned with the latest changelog.
- Prefer clarity over cleverness; mention optional variations if relevant.