sst-storage-db-web
v1.0.0
Published
A powerful MongoDB-like database for Next.js, React, and Node.js. Works in browser and server with optional file persistence.
Maintainers
Readme
🗄️ sst-storage-db-web
A powerful MongoDB-like database for Next.js, React, and Node.js. Works seamlessly in browser, server, and with optional file persistence.
✨ Features
- 🌐 Cross-Platform - Works in React (browser), Next.js (API routes), and Node.js
- 📄 MongoDB-like API - Familiar query syntax with collections and documents
- 🔍 Advanced Queries - Support for operators like
$lt,$gt,$in,$regex,$and,$or, etc. - 💾 Multiple Storage Options - In-memory (default), localStorage (browser), or file system (Node.js)
- 📦 Zero Dependencies - No external dependencies required
- 🔗 TypeScript Ready - Full type definitions included
- 🗂️ Key-Value Storage - Simple key-value operations alongside collections
- ⚡ Performance - Efficient in-memory operations with optional persistence
- 🔄 Export/Import - Backup and restore functionality
📦 Installation
npm install sst-storage-db-web🚀 Quick Start
Browser (React)
import { SSTStorage, BrowserStorageAdapter } from 'sst-storage-db-web';
// Initialize with localStorage persistence
const adapter = new BrowserStorageAdapter();
const storage = new SSTStorage({
databaseName: 'myApp',
adapter: adapter,
enableLogging: true
});
await storage.initialize();
// Use collections
const users = storage.collection('users');
await users.insert({ name: 'John Doe', email: '[email protected]' });
const allUsers = await users.find();Next.js API Route (Node.js)
import { SSTStorage, NodeFSAdapter } from 'sst-storage-db-web';
// Initialize with file system persistence
const adapter = new NodeFSAdapter('./data');
const storage = new SSTStorage({
databaseName: 'myApp',
adapter: adapter,
enableLogging: true
});
await storage.initialize();
// Use collections
const products = storage.collection('products');
await products.insert({ name: 'Product 1', price: 99.99 });In-Memory (No Persistence)
import { SSTStorage } from 'sst-storage-db-web';
const storage = new SSTStorage({ databaseName: 'memoryDB' });
await storage.initialize();
const data = storage.collection('temp');
await data.insert({ temporary: true });📖 API Documentation
SSTStorage Class
Constructor
const storage = new SSTStorage(options);Options:
databaseName(string): Database name (default: 'SSTStorage')adapter(Adapter): Storage adapter (default: none - in-memory)autoSave(boolean): Auto-save to storage (default: true)enableLogging(boolean): Enable console logging (default: false)maxCollections(number): Maximum collections (default: 100)maxDocuments(number): Max documents per collection (default: 50000)
Methods
initialize(): Promise<boolean>
Initialize the storage system.
await storage.initialize();collection(name): Collection
Get or create a collection.
const users = storage.collection('users');set(key, value): Promise<boolean>
Store a key-value pair.
await storage.set('config', { version: '1.0' });get(key): Promise<any>
Retrieve a value by key.
const config = await storage.get('config');delete(key): Promise<boolean>
Delete a key-value pair.
await storage.delete('config');Collection Class
CRUD Operations
insert(document): Promise<Document>
Insert a single document.
const user = await users.insert({ name: 'Alice', email: '[email protected]' });find(query?, options?): Promise<Document[]>
Find documents.
// Find all
const all = await users.find();
// With query
const adults = await users.find({ age: { $gte: 18 } });
// With options
const paginated = await users.find(
{ age: { $lt: 30 } },
{ sort: { name: 1 }, limit: 10, skip: 0 }
);findOne(query?): Promise<Document | null>
Find a single document.
const user = await users.findOne({ email: '[email protected]' });findById(id): Promise<Document | null>
Find by document ID.
const user = await users.findById(documentId);updateById(id, updateData): Promise<Document | null>
Update a document by ID.
const updated = await users.updateById(userId, {
$set: { age: 31, lastLogin: new Date().toISOString() }
});deleteById(id): Promise<Document | null>
Delete a document by ID.
const deleted = await users.deleteById(userId);Query Operators
// Comparison
await users.find({ age: { $gt: 18 } }); // Greater than
await users.find({ age: { $gte: 18 } }); // Greater or equal
await users.find({ age: { $lt: 65 } }); // Less than
await users.find({ age: { $ne: 30 } }); // Not equal
// Arrays
await users.find({ role: { $in: ['admin', 'user'] } });
// Strings
await users.find({ name: { $regex: '^John' } });
// Existence
await users.find({ email: { $exists: true } });Update Operators
// Set fields
await users.updateById(id, { $set: { status: 'active' } });
// Increment
await users.updateById(id, { $inc: { loginCount: 1 } });
// Array operations
await users.updateById(id, { $push: { tags: 'vip' } });
await users.updateById(id, { $pull: { tags: 'old' } });Aggregation
// Distinct values
const statuses = await users.distinct('status');
// Group by field
const grouped = await users.groupBy('role');
// Aggregation pipeline
const results = await users.aggregate([
{ $match: { status: 'active' } },
{ $sort: { name: 1 } },
{ $limit: 10 }
]);🔌 Storage Adapters
NodeFSAdapter (Server)
For Next.js API routes and Node.js:
import { SSTStorage, NodeFSAdapter } from 'sst-storage-db-web';
const adapter = new NodeFSAdapter('./database');
const storage = new SSTStorage({ adapter });
await storage.initialize();Methods:
load(databaseName)- Load from filesave(databaseName, data)- Save to fileexists(databaseName)- Check if existsdelete(databaseName)- Delete filelist()- List all databasesgetSize(databaseName)- Get file size
BrowserStorageAdapter (Client)
For React and browser applications:
import { SSTStorage, BrowserStorageAdapter } from 'sst-storage-db-web';
const adapter = new BrowserStorageAdapter('app_');
const storage = new SSTStorage({ adapter });
await storage.initialize();Methods:
load(databaseName)- Load from localStoragesave(databaseName, data)- Save to localStorageexists(databaseName)- Check if existsdelete(databaseName)- Delete entrylist()- List all databasesgetSize(databaseName)- Get size in bytesgetAvailableSpace()- Get available localStorage spaceclearAll()- Clear all databases
💡 Usage Examples
Next.js API Route
// pages/api/users.js
import { SSTStorage, NodeFSAdapter } from 'sst-storage-db-web';
let storage;
async function initStorage() {
if (!storage) {
storage = new SSTStorage({
adapter: new NodeFSAdapter('./data'),
databaseName: 'myapp'
});
await storage.initialize();
}
return storage;
}
export default async function handler(req, res) {
const storage = await initStorage();
if (req.method === 'POST') {
const users = storage.collection('users');
const user = await users.insert(req.body);
res.status(201).json(user);
} else if (req.method === 'GET') {
const users = storage.collection('users');
const allUsers = await users.find();
res.status(200).json(allUsers);
}
}React Component
import { useEffect, useState } from 'react';
import { SSTStorage, BrowserStorageAdapter } from 'sst-storage-db-web';
export default function UserList() {
const [users, setUsers] = useState([]);
const [storage, setStorage] = useState(null);
useEffect(() => {
const initStorage = async () => {
const adapter = new BrowserStorageAdapter();
const st = new SSTStorage({ adapter, databaseName: 'reactApp' });
await st.initialize();
setStorage(st);
// Load users
const usersCol = st.collection('users');
const allUsers = await usersCol.find();
setUsers(allUsers);
};
initStorage();
}, []);
const addUser = async (name, email) => {
if (!storage) return;
const usersCol = storage.collection('users');
const newUser = await usersCol.insert({ name, email });
setUsers([...users, newUser]);
};
return (
<div>
<h1>Users</h1>
{users.map(user => (
<div key={user._id}>{user.name} - {user.email}</div>
))}
<button onClick={() => addUser('John', '[email protected]')}>Add User</button>
</div>
);
}🆚 React (Browser) vs Next.js (Server)
| Feature | React | Next.js | |---------|-------|---------| | Storage | localStorage | File System | | Adapter | BrowserStorageAdapter | NodeFSAdapter | | Persistence | Limited (5-10MB) | Unlimited | | Use Case | Client-side cache | Server-side database | | Import | Client-side | Server-side (API routes) |
📝 License
MIT License - See LICENSE file for details
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
🆘 Support
For issues and questions, please visit the GitHub repository
