Client Setup
The setupEventSourcingDBClient function initializes a singleton EventSourcingDB client that is used by all other functions in this package. It verifies connectivity and authenticates with the server before the application starts processing events.
Example Application
The examples on this page reference the eventsourcing-demo application.
You can find the full example on GitHub: eventsourcing-demo
Basic Usage
import { setupEventSourcingDBClient } from "@nimbus/eventsourcingdb";
await setupEventSourcingDBClient({
url: new URL(process.env.ESDB_URL ?? ""),
apiToken: process.env.ESDB_API_TOKEN ?? "",
});Configuration Options
| Option | Type | Description |
|---|---|---|
url | URL | The URL of the EventSourcingDB server |
apiToken | string | The API token for authenticating with EventSourcingDB |
eventObservers | EventObserver[] | Optional array of event observers to start after initialization |
Initialization Behavior
When setupEventSourcingDBClient is called, it performs the following steps:
- Creates a new client instance with the provided URL and API token
- Pings the EventSourcingDB server to verify connectivity
- Validates the API token
- Starts any provided event observers in the background
If the connection or authentication fails, a GenericException is thrown and the error is logged.
Setup with Event Observers
You can provide event observers that will automatically start observing events after the client is initialized:
import { setupEventSourcingDBClient } from "@nimbus/eventsourcingdb";
import type { Event } from "eventsourcingdb";
await setupEventSourcingDBClient({
url: new URL(process.env.ESDB_URL ?? ""),
apiToken: process.env.ESDB_API_TOKEN ?? "",
eventObservers: [
{
subject: "/",
recursive: true,
eventHandler: (event: Event) => {
console.log("Received event:", event);
},
},
],
});See the Event Observer documentation for details on configuring observers.
Getting the Client
After initialization, use getEventSourcingDBClient to access the singleton client instance anywhere in your application:
import { getEventSourcingDBClient } from "@nimbus/eventsourcingdb";
const client = getEventSourcingDBClient();TIP
You typically don't need to call getEventSourcingDBClient directly. The writeEvents and readEvents functions handle this internally.
Error Handling
The setup function throws a GenericException in two cases:
| Error | Cause |
|---|---|
| Connection failure | The EventSourcingDB server is unreachable |
| Invalid API token | The provided API token could not be verified |
import { setupEventSourcingDBClient } from "@nimbus/eventsourcingdb";
try {
await setupEventSourcingDBClient({
url: new URL(process.env.ESDB_URL ?? ""),
apiToken: process.env.ESDB_API_TOKEN ?? "",
});
} catch (error) {
// GenericException:
// - "Could not connect to EventSourcingDB"
// - "Invalid API token. Please check your API token."
}