AceBase Realtime Database Client

raw JSON →
1.22.3 verified Wed Apr 22 auth: no javascript

AceBase Client is a JavaScript/TypeScript library designed to connect to and interact with a remote AceBase realtime database server. It provides functionalities for reading, writing, querying, and subscribing to real-time data changes within an AceBase database. The current stable version is 1.22.3, with an active release cadence that frequently addresses bug fixes and introduces minor features, often preceded by release candidates. This client acts as the bridge for applications to leverage AceBase's NoSQL, schemaless, object-tree data model, supporting complex queries and robust authentication mechanisms. Its primary differentiator is its tight integration with the AceBase server ecosystem, enabling efficient data synchronization and real-time event handling for connected applications, both in Node.js and browser environments.

error ReferenceError: AceBaseClient is not defined
cause Attempting to use `AceBaseClient` in a browser environment without loading the `browser.min.js` script, or using ESM import in a CommonJS-only context (or vice versa) without proper transpilation.
fix
For browsers, ensure <script src="..."> is loaded. For Node.js, verify import { AceBaseClient } from 'acebase-client'; for ESM or const { AceBaseClient } = require('acebase-client'); for CommonJS is used correctly based on your project's module type.
error Error: connect ECONNREFUSED <host>:<port>
cause The AceBase server is not running, is inaccessible, or the provided host and port configuration is incorrect, preventing the client from establishing a connection.
fix
Verify that the AceBase server is running, listening on the specified host and port, and that no firewall is blocking the connection. Double-check host, port, and https options in the AceBaseClient constructor.
error Error: Access denied (401) or Error: Authentication failed (403)
cause The client attempted to access a protected resource without valid authentication credentials, or the provided credentials (username/password, email/password, or access token) are incorrect or expired.
fix
Ensure correct credentials are provided to db.auth.signIn, signInWithEmail, or signInWithToken. If using tokens, ensure they are still valid. Check server-side authentication rules.
breaking The return format for `uncached sync()` operations changed in v1.22.0. Applications using `sync()` without caching might need adjustments.
fix Review usage of `db.ref().sync()` and adapt code to the new return format. Consult the AceBase documentation for specific details on the updated structure.
breaking The `isNetworkError` getter was split into `isNetworkError` and `isServerError` in v1.22.2. If you relied on `isNetworkError` to catch all server-related errors, your error handling logic might need to be updated.
fix Update error handling code to specifically check for `isServerError` in addition to `isNetworkError` where applicable, or use `instanceof AceBaseRequestError` for broader catching.
gotcha The `setAccessToken` method for automatic sign-in with a stored token was introduced in v1.8.0. For older client versions, handling offline sign-in requires different manual logic or reconnect strategies.
fix Upgrade to v1.8.0 or newer to use `db.auth.setAccessToken(accessToken)` for seamless sign-in on reconnection. For older versions, implement custom logic to re-authenticate manually upon `connect` event.
gotcha When using AceBase Client directly in the browser without a module bundler, you must include the `browser.min.js` script via a `<script>` tag. Standard `import` or `require` syntax will not work in this context.
fix For browser-only applications without bundlers, use `<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/acebase-client@latest/dist/browser.min.js"></script>`. For modern web development, use a module bundler like Webpack or Rollup to utilize `import` statements.
npm install acebase-client
yarn add acebase-client
pnpm add acebase-client

Demonstrates connecting to an AceBase server, logging an event, performing a read/write operation, and setting up a real-time subscription for data changes. Includes environment variable usage for configuration.

import { AceBaseClient } from 'acebase-client';

// Replace with your actual AceBase server details
const host = process.env.ACEBASE_HOST ?? 'localhost';
const port = parseInt(process.env.ACEBASE_PORT ?? '5757', 10);
const dbname = process.env.ACEBASE_DBNAME ?? 'mydb';
const https = (process.env.ACEBASE_HTTPS ?? 'false') === 'true';

const db = new AceBaseClient({ host, port, dbname, https });

db.ready(async () => {
    console.log('Connected to AceBase server.');

    // 1. Log an event to the database
    const logRef = db.ref('log');
    await logRef.push({
        user: 'guest_user',
        type: 'quickstart_connect',
        datetime: new Date().toISOString()
    });
    console.log('Logged connection event.');

    // 2. Write and read user data
    const userId = 'quickstart_user';
    const userRef = db.ref(`users/${userId}`);
    await userRef.set({ name: 'Jane Doe', email: 'jane@example.com', createdAt: new Date().toISOString() });
    console.log(`User '${userId}' created.`);

    const snapshot = await userRef.get();
    console.log(`Read user data: ${JSON.stringify(snapshot.val())}`);

    // 3. Subscribe to real-time changes on a 'todo' list
    const todoRef = userRef.child('todo');
    todoRef.on('child_added', (snapshot) => {
        const item = snapshot.val();
        console.log(`[REALTIME] Todo item added: ${item.text} (ID: ${snapshot.key})`);
    });

    // Add an item after a short delay to trigger the subscription
    setTimeout(async () => {
        await todoRef.push({ text: 'Learn AceBase', completed: false });
        console.log('Added a todo item.');
    }, 1000);

    // Optional: Sign in if authentication is enabled on the server
    // try {
    //     const authResult = await db.auth.signInWithEmail('admin@example.com', 'yourpassword');
    //     console.log(`Signed in as ${authResult.user.email}`);
    // } catch (error) {
    //     console.warn('Authentication failed (if server requires it):', error.message);
    // }

});

db.on('error', (error) => {
    console.error('AceBase Client Error:', error);
});