Skip to content

Latest commit

 

History

History
99 lines (75 loc) · 2.33 KB

File metadata and controls

99 lines (75 loc) · 2.33 KB

Advanced Usage

Quick Transactions (quickTx)

For simple, single-operation transactions, you can use quickTx to avoid writing a full callback.

import { SencilloDB, quickTx } from "sencillodb";

const db = new SencilloDB();
const qtx = quickTx(db);

// Execute a single operation
await qtx("create", {
  data: { name: "Bob" },
  collection: "users"
});

Resource Manager

createResourceManager allows you to enforce schemas and simplify interactions with a specific collection.

import { SencilloDB, createResourceManager } from "sencillodb";

const db = new SencilloDB();

const User = createResourceManager({
  db,
  collection: "users",
  schema: [
    ["name", String],
    ["age", Number]
  ],
  index: (user) => user.age >= 18 ? "adult" : "minor"
});

// Validates data against schema before insertion
await User.execute("create", {
  data: { name: "Charlie", age: 25 }
});

AOF Persistence

Enable AOF for better write performance.

const db = new SencilloDB({ 
  file: "./data.json", 
  aof: true 
});

// Writes are fast (appended to data.json.aof)
await db.transaction(async tx => {
  await tx.create({ collection: "logs", data: { msg: "Hello" } });
});

// Periodically compact the log
setInterval(async () => {
  await db.compact();
}, 60000); // Every minute

Collection-Level Persistence (Lazy Loading)

For handling larger datasets, use the folder option. This stores each collection in its own file and loads them on demand.

const db = new SencilloDB({ 
  folder: "./my_db_folder" 
});

// Collections are loaded only when accessed
await db.transaction(async tx => {
  // Loads 'users.json' (if exists), modifies it, and saves it back.
  await tx.create({ collection: "users", data: { name: "Dave" } });
  
  // 'products.json' is NOT loaded or touched.
});

Custom Storage Hooks

You can override the default file system storage by providing loadHook and saveHook in the constructor. This is useful for saving data to S3, a remote database, or local storage in a browser.

const db = new SencilloDB({
  loadHook: async () => {
    // Return JSON string from custom source
    return await fetchFromMyDatabase();
  },
  saveHook: async (jsonString) => {
    // Save JSON string to custom destination
    await saveToMyDatabase(jsonString);
  }
});