@anysoftinc/anydb-sdk
v0.5.1
Published
AnyDB TypeScript SDK for querying and transacting with Datomic databases
Downloads
742
Maintainers
Readme
AnyDB TypeScript SDK
TypeScript SDK for querying and transacting with Datomic databases via the AnyDB server.
Installation
npm install @anysoftinc/anydb-sdkQuick Start
import {
DatomicClient,
createAnyDBClient,
kw,
sym,
uuid,
} from "@anysoftinc/anydb-sdk";
// Create a client
const client = new DatomicClient({
baseUrl: "http://localhost:4000",
getAuthToken: () => process.env.ANYDB_TOKEN!,
});
// Create a database wrapper for convenience
const db = createAnyDBClient(client, "sql", "db-name");
// Symbolic query
const query = {
find: [[sym("pull"), sym("?e"), [kw("db/id"), kw("person/name")]]],
where: [[sym("?e"), kw("person/name"), "John Doe"]],
};
const rows = await db.query(query);
// Execute a transaction (keywordized keys, kw()/uuid() for values)
await db.transact([
{
["person/id"]: uuid("550e8400-e29b-41d4-a716-446655440000"),
["person/name"]: "John Doe",
},
]);Core Features
Database Operations
- Database Management - Create, list, and delete databases
- Transactions - Execute database transactions
- Queries - Execute Datalog queries with full EDN support
- Entity Lookup - Retrieve individual entities
- Datom Access - Raw datom queries with indexing
Query Types
Traditional array-based queries are not supported in v2.
Symbolic Queries (Type-safe)
import { sym, kw } from "@anysoftinc/anydb-sdk";
const query = {
find: [sym("?e"), sym("?name")],
where: [[sym("?e"), kw("person/name"), sym("?name")]],
};
const results = await db.query(query);QueryBuilder has been removed in v2.
QueryBuilder Benefits:
- Type Safety: All attributes use proper
Keywordobjects withkw() - IntelliSense: Full autocomplete for methods and parameters
- Structured Queries: No string concatenation or EDN parsing errors
- Fluent API: Chain methods for readable query construction
- Aggregations: Built-in support for count, sum, avg, min, max
- Direct Execution: Execute queries directly from the builder
Temporal Queries
// As-of queries
const pastResults = await client.query(query, [
{
"db/alias": "storage/db",
"as-of": 1000,
},
]);
// Since queries
const recentResults = await client.query(query, [
{
"db/alias": "storage/db",
since: 1000,
},
]);
// History queries
const allHistory = await client.query(query, [
{
"db/alias": "storage/db",
history: true,
},
]);SchemaBuilder and DatomicUtils have been removed in v2. Use plain tx maps with keywordized keys and kw()/uuid() for values.
Utility Functions
Utility helpers for tempids and entity builders were removed in v2.
Idempotent Schema Install
Use ensureAttributes(db, schemaEntities) to install attribute idents exactly once per database alias. It checks which idents already exist and only transacts the missing ones.
import { ensureAttributes, kw } from "@anysoftinc/anydb-sdk";
await ensureAttributes(db, [
{ "db/ident": kw("person/name"), "db/valueType": kw("db.type/string"), "db/cardinality": kw("db.cardinality/one") },
{ "db/ident": kw("person/age"), "db/valueType": kw("db.type/long"), "db/cardinality": kw("db.cardinality/one") },
]);Advanced Features
EDN Data Types
The SDK provides full support for Datomic's EDN data types:
import { sym, kw, uuid } from "@anysoftinc/anydb-sdk";
// Symbols for query variables
const entityVar = sym("?e");
// Keywords for attributes
const nameAttr = kw("person/name");
// UUIDs
const entityId = uuid("550e8400-e29b-41d4-a716-446655440000");Event Streaming
Subscribe to transaction reports via Server-Sent Events:
const eventSource = db.subscribeToEvents(
(event) => {
const txData = JSON.parse(event.data);
console.log("Transaction:", txData);
},
(error) => {
console.error("Connection error:", error);
}
);
// Close the connection when done
eventSource.close();Raw Datom Queries
Access the raw datom index for high-performance queries:
// Query EAVT index
const datoms = await db.datoms("eavt", "-", {
e: 12345,
limit: 100,
});
// Query AVET index for attribute values
const attributeValues = await db.datoms("avet", "-", {
a: ":person/name",
start: "A",
end: "B",
});Custom HTTP Configuration
const client = new DatomicClient({
baseUrl: "https://api.example.com",
timeout: 30000,
headers: {
Authorization: "Bearer token",
"X-Custom-Header": "value",
},
});NextAuth.js Integration
The SDK includes a NextAuth.js adapter for authentication:
import { AnyDBAdapter } from "@anysoftinc/anydb-sdk/nextauth-adapter";
import NextAuth from "next-auth";
export default NextAuth({
adapter: AnyDBAdapter(db),
providers: [
// Your providers
],
});
Cookie names per app (avoid collisions)
If multiple apps share a domain, configure distinct cookie names so sessions don’t collide.
```ts
import NextAuth from "next-auth";
import { AnyDBAdapter, createNextAuthCookies } from "@anysoftinc/anydb-sdk/nextauth-adapter";
// ai-pm-suite
export default NextAuth({
adapter: AnyDBAdapter(db),
cookies: createNextAuthCookies("ai-pm-suite", { style: "cookie" }),
// ... other config
});
// dashboard
export default NextAuth({
adapter: AnyDBAdapter(db),
cookies: createNextAuthCookies("dashboard", { style: "cookie" }),
// ... other config
});This produces names like ai-pm-suite.session.cookie, ai-pm-suite.callback.cookie, and ai-pm-suite.csrf.cookie (prefixed with __Host- in production). Clear existing cookies after changing names.
SSO across apps (shared DB)
If multiple apps use the same AnyDB auth database and you want single sign-on across them, derive cookie names from the database name so they all share the same cookie namespace:
import NextAuth from "next-auth";
import { AnyDBAdapter, createNextAuthCookiesFromDb } from "@anysoftinc/anydb-sdk/nextauth-adapter";
export default NextAuth({
adapter: AnyDBAdapter(db),
// Use DB name for cookie namespace to share sessions across apps
cookies: createNextAuthCookiesFromDb(db, { style: "cookie" }),
// ... other config
});Auth Helpers (Server-side)
Issue AnyDB-compatible HS256 tokens and normalize subjects consistently across apps:
import { createServiceTokenProvider, signFromSessionClaims } from "@anysoftinc/anydb-sdk/auth";
// 1) Service token provider (e.g., for adapters/bootstrap)
const getServiceToken = createServiceTokenProvider({
secret: process.env.JWT_SECRET!,
storageAlias: "dev",
dbName: "app",
iss: "my-app-service",
ttlSeconds: 3600,
});
// Use with DatomicClient
// new DatomicClient({ baseUrl, getAuthToken: getServiceToken })
// 2) Per-user token from NextAuth claims (re-signs JWS for AnyDB)
const token = signFromSessionClaims({
claims: nextAuthClaims, // from next-auth/jwt getToken()
secret: process.env.JWT_SECRET!,
storageAlias: "dev",
dbName: "app",
iss: "my-app-auth",
ttlSeconds: 900,
});Error Handling
The SDK provides detailed error information:
try {
const results = await db.query(invalidQuery);
} catch (error) {
if (error.message.includes("Datomic API error")) {
console.error("Server error:", error.message);
} else {
console.error("Client error:", error);
}
}TypeScript Support
Full TypeScript definitions are included:
import type {
QueryResult,
Transaction,
Entity,
Datom,
DatabaseDescriptor,
} from "@anysoftinc/anydb-sdk";
const processResults = (results: QueryResult): void => {
results.forEach((row) => {
console.log("Row:", row);
});
};Examples
See the examples directory for complete working examples:
- Console Example - Web-based query interface with Monaco Editor
- NextAuth.js Example - Authentication adapter for NextAuth.js
API Reference
DatomicClient
The main client class for interacting with the AnyDB server.
AnyDBClient
Convenience wrapper for working with a specific database.
Related
- AnyDB Server - Backend Clojure implementation
- Datomic Documentation - Official Datomic docs
