### Install ContextDB via NPM Source: https://context7.com/mmckegg/contextdb/llms.txt The standard command to install the ContextDB package into your Node.js project. ```bash npm install contextdb ``` -------------------------------- ### GET /generate Source: https://github.com/mmckegg/contextdb/blob/master/README.md Generates a datasource instance prepopulated with data based on provided matchers. ```APIDOC ## GET /generate ### Description Returns a datasource instance that maintains a live connection to the database based on the specified matchers and starting data. ### Method GET ### Parameters #### Query Parameters - **options** (Object) - Required - Contains 'data' (starting point) and 'matcherRefs' (array of refs). - **callback** (Function) - Required - Returns (err, datasource). ### Response #### Success Response (200) - **datasource** (Object) - An instance of JSON Context with live event streaming. ``` -------------------------------- ### Initialize ContextDB Instance Source: https://github.com/mmckegg/contextdb/blob/master/README.md Demonstrates how to require the module and initialize a ContextDB instance with a LevelDB database and specific matchers. ```javascript var LevelDB = require('level'); var ContextDB = require('contextdb'); var db = LevelDB(__dirname + '/test-db', { valueEncoding: 'json' }); var contextDB = ContextDB(db, { matchers: { 'items_for_parent': { item: 'items[id={.id}]', collection: 'items', match: { parentId: {$query: 'parentId'}, type: 'comment' }, allow: { change: true } }, 'current_user': { item: 'user', match: { type: 'user', id: 'user_123' } } }, primaryKey: 'id' }); ``` -------------------------------- ### Initialize ContextDB Source: https://github.com/mmckegg/contextdb/blob/master/README.md Initializes a new ContextDB instance by providing a LevelDB database and configuration options including matchers. ```APIDOC ## Initialize ContextDB ### Description Creates a new instance of ContextDB linked to a LevelDB database. This setup defines how data is indexed and retrieved via matchers. ### Method Constructor ### Parameters #### Request Body - **db** (Object) - Required - An instance of a levelup database. - **options** (Object) - Required - Configuration object. - **matchers** (Object) - Required - Named matchers for data filtering. - **primaryKey** (String) - Optional - Key to use as the primary index (default: 'id'). - **incrementingKey** (String) - Optional - Key for auto-incrementing IDs (default: '_seq'). - **timestamps** (Boolean) - Optional - Enable automatic timestamps (default: true). ### Request Example { "matchers": { "items": { "item": "items", "match": { "type": "item" } } }, "primaryKey": "id" } ``` -------------------------------- ### contextDB.generate Source: https://context7.com/mmckegg/contextdb/llms.txt Initializes a new datasource instance based on specific matchers and begins tracking live events. ```APIDOC ## contextDB.generate(options, callback) ### Description Creates a datasource instance that is prepopulated with data matching the provided criteria. It maintains a live connection to the database for real-time updates. ### Parameters #### Request Body - **options** (object) - Required - Configuration object containing 'data' (filter criteria) and 'matcherRefs' (array of strings). - **callback** (function) - Required - Function receiving (err, datasource). ### Response - **datasource** (object) - The initialized datasource instance. ``` -------------------------------- ### Initialize ContextDB Instance Source: https://context7.com/mmckegg/contextdb/llms.txt Configures a new ContextDB instance by wrapping a LevelDB database and defining matchers for data querying. Matchers use pattern matching to determine which objects belong to specific datasources. ```javascript var LevelDB = require('level') var ContextDB = require('contextdb') var db = LevelDB(__dirname + '/my-database', { valueEncoding: 'json' }) var contextDB = ContextDB(db, { matchers: { 'items_for_parent': { item: 'items[id={.id}]', collection: 'items', match: { parentId: {$query: 'parentId'}, type: 'comment' }, allow: { change: true } }, 'current_user': { item: 'user', match: { type: 'user', id: {$query: 'userId'} } }, 'site': { item: 'site', match: { type: 'site', id: {$query: 'site_id'} } } }, primaryKey: 'id', incrementingKey: '_seq', timestamps: true }) ``` -------------------------------- ### Generate Datasource and Handle Realtime Streams Source: https://github.com/mmckegg/contextdb/blob/master/README.md Illustrates generating a datasource from matchers and piping changes over a stream using Shoe for realtime updates. ```javascript var params = {parentId: 1, userId: 'user_123', token: 'some_unique_random_string'}; var matcherRefs = ['current_user', 'items_for_parent']; contextDB.generate(params, matcherRefs, function(err, datasource) { renderer.render('page', datasource, function(err, html) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end(html); }); }); ``` -------------------------------- ### Implement Real-time Server-Client Sync with Shoe Source: https://context7.com/mmckegg/contextdb/llms.txt Demonstrates how to use the Shoe websocket library to stream datasources between a Node.js server and a client. It handles token-based authentication and pipes change streams bidirectionally. ```javascript var Shoe = require('shoe') var http = require('http') var server = http.createServer() var userDatasources = {} function handleRequest(req, res, params) { contextDB.generate({ data: { site_id: params.siteId }, matcherRefs: ['site', 'items'] }, function(err, datasource) { var token = 'unique_token_' + Date.now() userDatasources[token] = datasource res.writeHead(200, {'Content-Type': 'text/html'}) res.end('...') }) } Shoe(function(stream) { var datasource = null stream.once('data', function(data) { var token = data.toString().trim() datasource = userDatasources[token] if (datasource) { stream.pipe(datasource.changeStream()).pipe(stream) } else { stream.close() } }) stream.once('end', function() { if (datasource) { datasource.destroy() userDatasources[datasource.data.token] = null } }) }).install(server, '/contexts') ``` -------------------------------- ### Apply Changes to Database Source: https://github.com/mmckegg/contextdb/blob/master/README.md Shows how to push new objects into the database using applyChange, which triggers notifications to relevant datasources. ```javascript var newObject = { id: 1, parentId: 'site', name: "Home", type: 'page' }; contextDB.applyChange(newObject); ``` -------------------------------- ### Generate ContextDB Datasource Source: https://context7.com/mmckegg/contextdb/llms.txt Generates a datasource instance pre-populated with data matching specified matchers. The datasource receives live events and allows changes to be pushed back to the database. It requires the 'contextDB' object and a callback function. ```javascript var site = { id: 'site-1', type: 'site', name: "My Site" } var item1 = { id: 'item-1', type: 'item', site_id: 'site-1', description: "Item 1" } var item2 = { id: 'item-2', type: 'item', site_id: 'site-1', description: "Item 2" } contextDB.applyChanges([site, item1, item2], function() { contextDB.generate({ data: { site_id: 'site-1' }, matcherRefs: ['site', 'items'] }, function(err, datasource) { if (err) { console.error('Failed to generate datasource:', err) return } console.log('Datasource data:', datasource.data) // Output: { site_id: 'site-1', site: { id: 'site-1', ... }, items: [{ id: 'item-1', ... }, { id: 'item-2', ... }] } // Listen for real-time changes datasource.on('change', function(object, changeInfo) { console.log('Object changed:', object.id, changeInfo.matcher.ref) }) // Emit sync event when initial data is loaded datasource.on('sync', function() { console.log('Datasource synchronized') }) // Clean up when done // datasource.destroy() }) }) ``` -------------------------------- ### datasource.emitChangesSince Source: https://context7.com/mmckegg/contextdb/llms.txt Synchronizes clients by replaying changes that occurred after a specific timestamp. ```APIDOC ## datasource.emitChangesSince(timestamp) ### Description Emits all changes (including deletions) that have occurred since the provided timestamp, useful for offline synchronization. ### Parameters - **timestamp** (number) - Required - The epoch timestamp to start replay from. ``` -------------------------------- ### POST /applyChange Source: https://github.com/mmckegg/contextdb/blob/master/README.md Applies a single change to the database and notifies all relevant datasources. ```APIDOC ## POST /applyChange ### Description Persists an object into the database and triggers updates for any active datasources listening to the affected data. ### Method POST ### Parameters #### Request Body - **object** (Object) - Required - The data object to save. - **cb** (Function) - Optional - Callback function executed after the change is applied. ### Request Example { "id": 1, "name": "Home", "type": "page" } ``` -------------------------------- ### datasource.pushChange Source: https://context7.com/mmckegg/contextdb/llms.txt Propagates local changes to the database and other connected datasources. ```APIDOC ## datasource.pushChange(object, changeInfo) ### Description Validates and pushes a change to the database. If successful, the change is propagated to all active listeners. ### Parameters - **object** (object) - Required - The data object to update. - **changeInfo** (object) - Required - Metadata about the change (e.g., { verifiedChange: true }). ``` -------------------------------- ### Apply Batch Changes to ContextDB Source: https://context7.com/mmckegg/contextdb/llms.txt Efficiently inserts multiple objects into the database in a single operation. Notifies all relevant datasources once the batch process completes. ```javascript var site = { id: 'site-1', type: 'site', name: "Cool Site" } var item1 = { id: 'item-1', type: 'item', site_id: site.id, description: "First Item" } var item2 = { id: 'item-2', type: 'item', site_id: site.id, description: "Second Item" } contextDB.applyChanges([site, item1, item2], function(err) { if (err) { console.error('Batch insert failed:', err) return } console.log('Successfully inserted 3 objects') }) ``` -------------------------------- ### Apply Single Change to ContextDB Source: https://context7.com/mmckegg/contextdb/llms.txt Pushes a single object into the database and triggers notifications for relevant datasources. Automatically handles timestamps if enabled in the configuration. ```javascript var newPage = { id: 'page-1', parentId: 'site-root', name: "Home Page", type: 'page' } contextDB.applyChange(newPage, function(err) { if (err) { console.error('Failed to apply change:', err) return } console.log('Object saved with timestamps:', newPage) }) ``` -------------------------------- ### Force Database Reindexing in ContextDB Source: https://context7.com/mmckegg/contextdb/llms.txt Manually trigger a database reindex operation. This utility emits 'reindex' and 'indexed' events and accepts a callback function to execute upon completion of the rebuild. ```javascript contextDB.on('reindex', function() { console.log('Reindexing started...') }) contextDB.on('indexed', function() { console.log('Reindexing completed') }) contextDB.forceIndex(function() { console.log('Index rebuild finished') }) ``` -------------------------------- ### Retrieve All Matched Objects in ContextDB Source: https://context7.com/mmckegg/contextdb/llms.txt Retrieves all current objects matching the datasource's matchers. It returns an array of all matched values and requires a callback function to handle the results or errors. ```javascript contextDB.generate({ data: { site_id: 'site-1' }, matcherRefs: ['site', 'items'] }, function(err, datasource) { datasource.getChanges(function(err, results) { if (err) { console.error('Failed to get changes:', err) return } console.log('All matched objects:', results) // Output: [{ id: 'site-1', type: 'site', ... }, { id: 'item-1', ... }, { id: 'item-2', ... }] }) }) ``` -------------------------------- ### datasource.getChanges Source: https://context7.com/mmckegg/contextdb/llms.txt Retrieves the current state of all objects matching the datasource criteria. ```APIDOC ## datasource.getChanges(callback) ### Description Fetches the current set of objects currently matched by the datasource. ### Parameters - **callback** (function) - Required - Function receiving (err, results) where results is an array of objects. ``` -------------------------------- ### Push Changes to ContextDB Database Source: https://context7.com/mmckegg/contextdb/llms.txt Pushes changes from a datasource back to the database. Changes are validated against matchers and propagated to other listening datasources. This function is part of the datasource object and requires the object to be changed and change information. ```javascript contextDB.generate({ data: { site_id: 'site-1' }, matcherRefs: ['site', 'items'] }, function(err, datasource1) { contextDB.generate({ data: { site_id: 'site-1' }, matcherRefs: ['site', 'items'] }, function(err, datasource2) { // Listen for changes from other datasources datasource2.on('change', function(object, changeInfo) { if (changeInfo.source === contextDB) { console.log('Received change from database:', object.description) } }) // Push a change from datasource1 - it will be received by datasource2 var updatedItem = { id: 'item-1', type: 'item', site_id: 'site-1', description: "Updated by datasource 1" } datasource1.pushChange(updatedItem, { verifiedChange: true }) // datasource2 will receive this change via its 'change' event }) }) ``` -------------------------------- ### Emit ContextDB Changes Since Timestamp Source: https://context7.com/mmckegg/contextdb/llms.txt Emits all changes (including deletions) that have occurred since a specified timestamp. This is useful for synchronizing clients that were offline. It requires a timestamp and attaches a 'change' event listener. ```javascript contextDB.generate({ data: { site_id: 'site-1' }, matcherRefs: ['site', 'items'] }, function(err, datasource) { // Store timestamp before going offline var lastSyncTimestamp = Date.now() // Simulate offline changes being made by other sources setTimeout(function() { var newItem = { id: 'item-3', type: 'item', site_id: 'site-1', description: "Added while offline" } contextDB.applyChange(newItem) }, 100) // Later, reconnect and request changes since last sync setTimeout(function() { datasource.on('change', function(object, changeInfo) { if (changeInfo.verfiedChange) { console.log('Received missed change:', object.id) } }) datasource.emitChangesSince(lastSyncTimestamp) // Will emit all objects that were created/updated/deleted after lastSyncTimestamp }, 200) }) ``` -------------------------------- ### Delete Objects in ContextDB Source: https://context7.com/mmckegg/contextdb/llms.txt Soft-deletes objects in ContextDB by setting the `_deleted` flag to `true`. This removes the object from datasources and records a `deleted_at` timestamp if enabled. The deletion is performed using `datasource.pushChange`. ```javascript contextDB.generate({ data: { site_id: 'site-1' }, matcherRefs: ['site', 'items'] }, function(err, datasource) { console.log('Initial items:', datasource.data.items.length) // Output: Initial items: 2 // Delete an item by setting _deleted flag var deletedItem = { id: 'item-2', type: 'item', site_id: 'site-1', _deleted: true } datasource.pushChange(deletedItem, { verifiedChange: true }) console.log('Items after delete:', datasource.data.items.length) // Output: Items after delete: 1 // The deleted_at timestamp is automatically set }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.