TypeScript & Node.js SDK

SPD2 + TLS Client & Pool, native bigint fidelity, DecimalParam, ORM query builder, and migrations.

1 min read Official SDKs (12 Languages)

The official TypeScript/JavaScript driver and ORM (spyddb) speaks SpydWire v2 (SPD2) binary framing over TCP/TLS with native bigint fidelity for u64/i64, exact Decimal precision, connection pooling, prepared statements, interactive transactions, schema diffing, and checksummed migrations.

1. Installation#

sh
npm install spyddb

Requires Node.js 20+ (Node.js 22+ runs TypeScript files natively with zero build configuration).

2. Connecting (Client, SCRAM, TLS & mTLS)#

ts
import { Client } from "spyddb";

const client = await Client.connect(
  "spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN&tls=1&ca=docker/tls/ca.crt&server_name=localhost",
);

try {
  const result = await client.execute(
    "users | where active == $1 | pick id, email, name | sort id | take 10",
    [true],
  );
  for (const row of result.dicts) {
    console.log(row);
  }
} finally {
  await client.close();
}

SCRAM-SHA-256 & Options Object with mTLS#

ts
import { Client } from "spyddb";

const client = await Client.connect({
  host: "db.internal",
  port: 5433,
  user: "alice",
  passwordEnv: "SPYD_PASSWORD",
  ca: "/etc/spyd/ca.crt",
  serverName: "db.internal",
  clientCert: "/etc/spyd/client.crt",
  clientKey: "/etc/spyd/client.key",
  timeout: 30_000,
});

3. Big Integers, Exact Decimals, Vectors & Geo Values#

SpydDB enforces strict precision: integers exceeding Number.MAX_SAFE_INTEGER return as JavaScript bigint, and large parameter integers must use bigint (or UIntValue / IntValue) rather than unsafe number.

ts
import { Client, DecimalParam, GeoPoint, UIntValue, VectorValue } from "spyddb";

const client = await Client.connect("spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN");

// 1. Exact 64-bit unsigned integer (2^64 - 1)
await client.execute("counters | insert { id: $1, total: $2 }", [
  new UIntValue(1, 64),
  18446744073709551615n,
]);
const row = (await client.execute("counters | where id == 1 | pick total")).one();
console.log(typeof row.total, row.total); // "bigint", 18446744073709551615n

// 2. Exact fixed-point Decimal via DecimalParam + cast
await client.execute(
  "orders | insert { id: $1, total: cast($2 as decimal(12, 2)) }",
  [10, new DecimalParam("19.99", 12, 2)],
);

// 3. HNSW vector & GeoPoint binding
await client.execute(
  "places | where nearest(embedding, $1, 5) | pick id, name",
  [new VectorValue([0.21, -0.44, 0.87, 0.11])],
);

4. Prepared Statements, Transactions & Pooling#

ts
import { Pool, SpydConflictError } from "spyddb";

const pool = new Pool(
  "spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN&tls=1&ca=docker/tls/ca.crt",
  16, // maxOpen
  4,  // maxIdle
);

try {
  // Prepared statement lifecycle on an acquired connection
  const conn = await pool.acquire();
  try {
    await conn.useDatabase("default");
    const stmt = await conn.prepare("orders | where status == $1 | pick id, total | take 50");
    try {
      const paid = await conn.executePrepared(stmt.id, ["paid"]);
      console.log("Paid count:", paid.rows.length);
    } finally {
      await conn.closePrepared(stmt.id);
    }

    // Explicit ACID transaction
    await conn.begin();
    try {
      await conn.execute(
        "accounts | where id == $1 | set { balance: balance_delta(balance, 0, 100000, -100) }",
        [1],
      );
      await conn.execute(
        "accounts | where id == $1 | set { balance: balance_delta(balance, 0, 100000, +100) }",
        [2],
      );
      await conn.commit();
    } catch (err) {
      await conn.rollback();
      if (err instanceof SpydConflictError) {
        console.warn("SSI conflict — retry transaction");
      }
      throw err;
    }
  } finally {
    pool.release(conn);
  }
} finally {
  await pool.close();
}

5. TypeScript ORM, Query Builder & Migrations#

ts
import {
  Database, Decimal, Migration, Model, avg, count, f, sum,
} from "spyddb";

class User extends Model {
  static collection = "users";
  static fields = {
    id: f.u64({ primary: true, autoIncrement: true }),
    email: f.string(160, { unique: true, nullable: false }),
    name: f.string(80, { nullable: false }),
    balance: f.decimal(12, 2, { default: new Decimal(0n, 2) }),
    active: f.bool({ default: true }),
    joined: f.timestamp(),
  };
}

const db = await Database.connect(
  "spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN",
  { models: [User] },
);

// Create collections & apply additive schema changes safely
await db.createAll();
await db.sync();

// Insert, mutate, and save
const ada = await User.create({ email: "ada@example.test", name: "Ada" });
ada.balance = new Decimal("12.50");
await ada.save();

// Fluent typed query builder
const activeUsers = await User.where(
  User.col("active").eq(true).and(User.col("name").ne("")),
)
  .orderBy("-joined")
  .limit(20)
  .all();

// Group by & aggregates
const summary = await User.query()
  .aggregate(sum(User.col("balance")).as("total"), count().as("n"), avg(User.col("balance")).as("mean"))
  .one();

// Async generator pagination across large collections
for await (const batch of User.query().iterate(500)) {
  console.log("Batch size:", batch.length);
}

// Inspect execution plan
console.log(await User.where(User.col("active").eq(true)).explain());

// Versioned SHA-256 migrations
await db.migrate([
  new Migration(
    "0001_create_audit_notes",
    ["create collection audit_notes { id: u64 primary auto_increment, note: text }"],
    ["drop collection if exists audit_notes"],
  ),
]);

await db.close();

6. Typed Error Handling#

All failures throw typed subclasses of SpydError:

  • SpydConnectionError, SpydTimeoutError, SpydProtocolError
  • SpydAuthenticationError, SpydPermissionError
  • SpydConflictError (retryable SSI transaction serialization conflict)
  • SpydConstraintError, SpydSchemaError, SpydTypeError, SpydValueError
  • SpydNoResultError, SpydMultipleResultsError, SpydCancelledError, SpydResourceError, SpydQueryError