Skip to content

abmercy035/localclientdb

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“¦ localclientdb

npm version bundle size CDN TypeScript

localclientdb a lightweight JavaScript/TypeScript library, that provides a schema-based, MongoDB-like API as client-side database built on top of localForage. Supports IndexedDB, WebSQL, and LocalStorage with MongoDB-like collection methods and validation.

New GUI feature: With flexible page setup via startGui

Perfect for local-first apps, prototypes, or applications with offline-first features.


βœ… Features

  • πŸ“ Collection System β€” Mimics MongoDB-style collection handling.
  • ✍️ CRUD Operations β€” Insert, find, update, and delete documents
  • 🧱 Schema Validation β€” Define Schema validation or collections and validate inserts by type and required checks
  • πŸ” Query Support β€” Find documents with simple object queries.
  • βš™οΈ Pluggable Storage β€” IndexedDB (default), WebSQL, LocalStorage
  • 🧠 In-browser Only β€” No server required
  • ⚑ Simple β€” MongoDB-like chainable API, synchronous-looking API (Promise-based)

NEW πŸš€πŸ”₯

  • πŸ–ΌοΈ Built-in GUI β€” Easily inspect, modify, and visualize your data!

πŸ“¦ Installation

npm install localclientdb

# or beta version
npm install localclientdb@beta

CDN (for Vanilla JS)

<script src="https://unpkg.com/localclientdb@beta/dist/localclientdb.umd.js"></script>

<!-- Minified -->
<script src="https://unpkg.com/localclientdb@beta/dist/localclientdb.umd.min.js"></script>

Other import Script for compatibility purpose

<!-- cjs -->
<script src="https://unpkg.com/localclientdb@beta/dist/localclientdb.cjs.js"></script>

<!-- ems -->
<script src="https://unpkg.com/localclientdb@beta/dist/localclientdb.esm.js"></script>

🧠 New Feature: Visual Database GUI

Inspect your collections visually by launching the built-in GUI.

βž• Usage (React or Vanilla):

import { startGui } from 'localclientdb';

startGui({
  name: 'NoteApp',
  storeNames: ['notes', 'users'],  // Optional: Required to display docs in specific collections, else fallback/default is used : ["default"] 
  mountId: 'my-gui-root',          // Optional: div ID to mount GUI (defaults to body)
  toggleBtn: true                  // Optional: shows toggle button to toggle Gui interface

});

πŸ§ͺ With HTML + CDN

<body>
  <div id="my-gui-root"></div>
  <script>
    const db = LocalClientDB.localClientDB();
    db.connect({ name: "MyDB" });                   //connect/create to local database
    db.createCollection(
      "tasks",                                      //collection name
     {title: { type: "string", required: true },    //schema object
    });

    LocalClientDB.startGui({
      name: "MyDB",                 //connect to local database you want to view
      storeNames: ["tasks"],        //list of collections available in database or to be created. 
      mountId: "my-gui-root"        // Optional: div ID to mount GUI (defaults to body)
      toggleBtn: true               // Optional: shows toggle button to toggle Gui interface
    });
  </script>
</body>

You can also create a standalone page (e.g. /public/db.html) to inspect your app’s local data.


πŸ› οΈ Usage Example

Project Structure

src/
β”œβ”€β”€ schemas/                  # Define collection schemas
β”‚   └── note.schema.ts
β”œβ”€β”€ components/               # NoteApp pages
β”‚   └── Gui.tsx               # Gui display component/page
|   └── Note.tsx              # Note component/page
β”œβ”€β”€ localClientDB.config.ts   # DB config
β”œβ”€β”€ App.tsx                   # React entry

πŸ”§ LocalClientDB API Overview

connect(config);   // config uses interface of StorageConfig

/* interface StorageConfig {
	name: string;
	storeName?: string;
	driver?: string | string[];
} */

createCollection(name, schema);
insertOne(collection, doc)         // or collection.insertOne(doc)
insertMany(collection, doc[])         // or collection.insertMany(doc[])
find(collection, query)            // or collection.find(query)
findById(collection, _id)          // or collection.findById(_id)
findOne(collection, query)         // or collection.findOne(query)
updateOne(collection, query, update)       // or collection.updateOne(query, docUpdateData)
deleteById(collection, _id)        // or collection.deleteById(_id)
deleteOne(collection, query)       // or collection.deleteOne(query)
getAllDocs(collection)             // or collection.getAllDocs()
dropCollection(collection)         // or collection.dropCollection()

1. Import, config, Initialize

Then Export for usage across application

// localClientDB.config.ts		

import { localClientDB, driver } from "localclientdb";

// Optional: Set a specific driver
await localClientDB().setDriver(driver.INDEXEDDB);

// Connect (config)
const db = localClientDB();

db.connect({ name: 'NoteApp' })

// export database instance
export default db

With CDN in Vanilla JS

<script>

  const db = localclientdb.localClientDB();

await db.setDriver(driver.INDEXEDDB);  // Optional except you want change driver 
/* 
drivers are available throught 
import {driver} from  "localclientdb"
driver returns/expose the following

	"INDEXEDDB": for INDEXEDDB
	"WEBSQL": for WEBSQL
	"LOCALSTORAGE": for LOCALSTORAGE
 */ 


  db.connect({ name: "localDB", storeName: "users" });

  const users = db.createCollection("users", {
    name: { type: "string", required: true },
    age: "number",
  });

  users.insertOne({ name: "Anna", age: 21 });
</script>

2. Create a Collection with a schema (for model)

Note: This an example using React

//note.schema.ts			

// import db instance declare/create/init collection and collection schema.
import db from "./localClientlDB.config";

export const noteschema = {
	title: "string",
	content: "string",
	date: "string",
}


// name of collection = note (just like mongoose model)
export const noteSchema = db.createCollection("notes", noteschema)

3. Insert Data

// App.tsx
// a simple use case inside of App.jsx
import { useState } from "react";
import { noteSchema } from "./schemas/note.schema";

const [notes, setNotes] = useState([])
const [note, setNote] = useState({ title: "", content: "", id: null })

  const createNote = async (data: typeof noteSchema) => {
    if (!data.title || !data.content) return;
      const newNote = await noteSchema.insertOne({
        ...data,
        date: new Date().toISOString(),
      });
      setNotes([...notes, newNote]);
    setNote({ title: "", content: "", id: null });
}

  const deleteNote = async (id : string) => {
   await noteSchema.deleteOne({ _id: id });
    setNotes(notes.filter(n => n._id !== id));
}
 

4. Query Data

const all = await noteSchema.getAllDocs();
const note = await noteSchema.findOne({ title: "Welcome" });
const young = await users.find({ age: 22 });

5. Update & Delete

await noteSchema.updateOne({ title: "Old" }, { title: "New" });
await noteSchema.deleteOne({ _id: "doc_id" });
await noteSchema.deleteById("some_doc_id");

6. Drop a Collection

await noteSchema.drop();

πŸ”Œ Storage Drivers

import { driver } from "localclientdb";

// IndexedDB (default)
await db.setDriver(driver.INDEXEDDB);

// Switch to WebSQL or LocalStorage
await db.setDriver(driver.WEBSQL);
await db.setDriver(driver.LOCALSTORAGE);

πŸ” Schema Validation

db.createCollection("books", {
  title: { type: "string", required: true },
  pages: "number", // shorthand
});

Validation errors will be thrown if the inserted data doesn't match the schema.


🀝 Contributing

  1. Fork the repo
  2. git checkout -b feature-name
  3. Make changes
  4. Push and open a pull request!

Have questions or suggestions? Open an issue.


πŸ“„ License

This project is licensed under the MIT License Β© Dev Abraham


🧩 Socials

X (fomerly twitter): @DevAbraham035

LinkedIn: @javascriptenthusiat

About

localclientdb is a lightweight JavaScript/TypeScript library designed to simulate a backend database on the client-side, particularly useful for frontend development, offline-first applications, and prototyping. It provides a MongoDB-like API and supports IndexedDB, WebSQL, and LocalStorage as storage backends. It can be used with various frontend.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors