npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

webcake-data

v1.0.10

Published

A modern JavaScript/TypeScript client library for WebCake database operations with MongoDB-like query interface

Downloads

252

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-data

Quick 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 URL
  • config.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 token
  • config.headers (object, optional): Additional headers
  • config.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 collection
  • insertOne(tableName, fields) - Insert a single record
  • insertMany(tableName, records) - Insert multiple records
  • query(tableName, queryParams) - Query records
  • updateById(tableName, id, fields) - Update record by ID
  • updateOne(tableName, filters, fields) - Update one record
  • updateMany(tableName, filters, fields) - Update multiple records
  • deleteById(tableName, id) - Delete record by ID
  • deleteOne(tableName, filters) - Delete one record
  • deleteMany(tableName, filters) - Delete multiple records
  • count(tableName, filters) - Count records
  • exists(tableName, filters) - Check if records exist

DBModel

Model class for collection operations.

Methods

  • create(data) - Create a new document
  • insertMany(dataArray) - Create multiple documents
  • find(filters) - Find documents (returns QueryBuilder)
  • findOne(filters, options) - Find one document with optional select/sort/populate
  • findById(id, options) - Find document by ID with optional select/sort/populate
  • updateOne(filters, updateData) - Update one document
  • findByIdAndUpdate(id, updateData, options) - Update document by ID
  • findOneAndUpdate(filters, updateData) - Find and update one document
  • updateMany(filters, updateData) - Update multiple documents
  • deleteOne(filters) - Delete one document
  • findByIdAndDelete(id) - Delete document by ID
  • findOneAndDelete(filters) - Find and delete one document
  • deleteMany(filters) - Delete multiple documents
  • countDocuments(filters) - Count documents
  • exists(filters) - Check if documents exist

findOne/findById options:

  • select (string | string[]): Fields to return
  • sort (object): Sort order applied before taking the first record
  • populate (object | object[]): Populate configuration(s) identical to QueryBuilder.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 filter
  • gt(field, value) - Greater than filter
  • gte(field, value) - Greater than or equal filter
  • lt(field, value) - Less than filter
  • lte(field, value) - Less than or equal filter
  • in(field, values) - In array filter
  • nin(field, values) - Not in array filter
  • ne(field, value) - Not equal filter
  • between(field, value1, value2) - Between values filter
  • like(field, pattern) - Pattern matching filter
  • sort(sortObj) - Sort results
  • limit(n) - Limit number of results
  • skip(n) - Skip number of results
  • select(fields) - Select specific fields
  • populate(config) - Populate related data
  • exec() - 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:prod

Build 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 browsers
  • webcake-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:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes and add tests
  4. Run the build: npm run build
  5. Commit your changes (git commit -m 'Add some amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. 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.