### Quick start example Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/core.md A basic example demonstrating how to initialize the YDB driver and wait for it to be ready. ```typescript import { Driver } from '@ydbjs/core' const driver = new Driver(process.env['YDB_CONNECTION_STRING'] || 'grpc://localhost:2136/local') await driver.ready() // use the driver with Query/Topic or low-level clients await driver.close() ``` -------------------------------- ### Setup Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/coordination/README.md Installs dependencies, builds packages, and navigates to the coordination examples directory. Also shows how to set the YDB connection string. ```bash # From the repository root npm install npm run build cd examples/coordination ``` ```bash export YDB_CONNECTION_STRING=grpc://localhost:2136/local ``` -------------------------------- ### Runnable Examples Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/drizzle/getting-started.md Instructions to run the compact TypeScript CLI example from the SDK repository. ```bash cd examples/drizzle-adapter npm install npm start ``` -------------------------------- ### Run the example Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/diagnostics/README.md Install dependencies and start the example with a default connection string. ```sh npm install YDB_CONNECTION_STRING=grpc://localhost:2136/local npm start ``` -------------------------------- ### Query Example Setup Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/README.MD Setup instructions for the SQL queries example. ```bash cd examples/query npm install && npm start ``` -------------------------------- ### Serverless Example Setup Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/README.MD Setup instructions for the serverless considerations example. ```bash cd examples/sls npm install && npm start ``` -------------------------------- ### API Example Setup Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/README.MD Setup instructions for the low-level API usage example. ```bash cd examples/api npm install && npm start ``` -------------------------------- ### Install Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/drizzle/getting-started.md Install the Drizzle adapter and drizzle-orm using npm. ```sh npm install @ydbjs/drizzle-adapter drizzle-orm ``` -------------------------------- ### Getting Started: Using direct factories Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/topic/README.md Example demonstrating how to use direct factory functions for creating readers and writers. ```ts import { Driver } from '@ydbjs/core' import { createTopicReader, createTopicTxReader } from '@ydbjs/topic/reader' import { createTopicWriter, createTopicTxWriter } from '@ydbjs/topic/writer' const driver = new Driver(process.env['YDB_CONNECTION_STRING']!) await driver.ready() await using reader = createTopicReader(driver, { topic: '/Root/my-topic', consumer: 'my-consumer', }) await using writer = createTopicWriter(driver, { topic: '/Root/my-topic', producer: 'my-producer', }) ``` -------------------------------- ### FSM Example Setup Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/README.MD Setup instructions for the FSM runtime usage example. ```bash cd examples/fsm npm install && npm start ``` -------------------------------- ### Running the example Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/fsm/README.md Commands to navigate to the example directory, install dependencies, and run the example. ```bash cd examples/fsm npm install npm start ``` -------------------------------- ### Getting Started: Using the top-level client Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/topic/README.md Example demonstrating how to create and use a reader and writer with the top-level topic client. ```ts import { Driver } from '@ydbjs/core' import { topic } from '@ydbjs/topic' const driver = new Driver(process.env['YDB_CONNECTION_STRING']!) await driver.ready() const t = topic(driver) // Reader await using reader = t.createReader({ topic: '/Root/my-topic', consumer: 'my-consumer', }) for await (const batch of reader.read()) { // Process messages for (const msg of batch) console.log(new TextDecoder().decode(msg.payload)) // Commit processed offsets (see performance note below) await reader.commit(batch) } // Writer await using writer = t.createWriter({ topic: '/Root/my-topic', producer: 'my-producer', }) writer.write(new TextEncoder().encode('Hello, YDB!')) await writer.flush() ``` -------------------------------- ### Topic Example Setup Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/README.MD Setup instructions for the Topic reader/writer and transactional usage example. ```bash cd examples/topic npm install && npm start ``` -------------------------------- ### Service Account Example Setup Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/README.MD Setup instructions for the Yandex Cloud Service Account authentication example. ```bash cd examples/service-account npm install && npm start ``` -------------------------------- ### Low-level Service Client Example Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/core.md Example of creating and using a low-level service client, specifically for the DiscoveryService. ```typescript import { DiscoveryServiceDefinition } from '@ydbjs/api/discovery' const discovery = driver.createClient(DiscoveryServiceDefinition) const endpoints = await discovery.listEndpoints({ database: driver.database }) ``` -------------------------------- ### TLS Example Setup Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/README.MD Setup instructions for the TLS with custom CA, mTLS example. ```bash cd examples/tls npm install && npm start ``` -------------------------------- ### Telemetry Example Setup Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/README.MD Setup instructions for the OpenTelemetry tracing + metrics example. ```bash cd examples/telemetry npm install && npm start ``` -------------------------------- ### Drizzle Adapter Example Setup Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/README.MD Setup instructions for the Drizzle ORM adapter example. ```bash cd examples/drizzle-adapter npm install && npm start ``` -------------------------------- ### Coordination Example Setup Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/README.MD Setup instructions for the Coordination nodes, distributed semaphores, leader election example. ```bash cd examples/coordination npm install && npm start ``` -------------------------------- ### Quick Setup for AI Assistants Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/query/SECURITY.md Copies example AI instruction files to the project root for different AI assistants. ```bash # For Cursor users cp node_modules/@ydbjs/query/ai-instructions/.cursorrules.example .cursorrules # For GitHub Copilot users cp node_modules/@ydbjs/query/ai-instructions/.copilot-instructions.example.md .copilot-instructions.md # For general AI assistants cp node_modules/@ydbjs/query/ai-instructions/.instructions.example.md .instructions.md # OR cp node_modules/@ydbjs/query/ai-instructions/.ai-instructions.example.md .ai-instructions.md ``` -------------------------------- ### Quick Setup Commands Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/query/ai-instructions/README.md Commands to copy example AI instruction files to the project root for different AI assistants. ```bash cp node_modules/@ydbjs/query/ai-instructions/.cursorrules.example .cursorrules # For GitHub Copilot cp node_modules/@ydbjs/query/ai-instructions/.copilot-instructions.example.md .copilot-instructions.md # For general AI assistants cp node_modules/@ydbjs/query/ai-instructions/.instructions.example.md .instructions.md # OR cp node_modules/@ydbjs/query/ai-instructions/.ai-instructions.example.md .ai-instructions.md ``` -------------------------------- ### Quick Setup for AI Assistant Configuration Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/query/README.md Commands to copy example AI assistant configuration files to the project root. ```bash # Choose the appropriate file for your AI assistant cp node_modules/@ydbjs/query/ai-instructions/.cursorrules.example .cursorrules cp node_modules/@ydbjs/query/ai-instructions/.instructions.example.md .instructions.md ``` -------------------------------- ### Environment-Based Auto-Detection Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/core.md Example demonstrating the use of EnvironCredentialsProvider for automatic authentication strategy detection. ```typescript import { Driver } from '@ydbjs/core' import { EnvironCredentialsProvider } from '@ydbjs/auth/environ' let cs = process.env['YDB_CONNECTION_STRING']! let creds = new EnvironCredentialsProvider(cs) const driver = new Driver(cs, { credentialsProvider: creds, secureOptions: creds.secureOptions, }) await driver.ready() ``` -------------------------------- ### Setup Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/CONTRIBUTING.md Clones the repository and installs dependencies. ```bash git clone https://github.com/ydb-platform/ydb-js-sdk.git cd ydb-js-sdk npm ci ``` -------------------------------- ### Quick Start Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/fsm/README.md A basic example demonstrating the creation and usage of a finite state machine runtime with typed states, events, effects, and outputs. ```ts import { createMachineRuntime } from '@ydbjs/fsm' type State = 'idle' | 'running' | 'done' type Event = | { type: 'counter.start' } | { type: 'counter.increment'; step?: number } | { type: 'counter.finish' } type Effect = { type: 'counter.log'; message: string } type Output = { type: 'counter.state'; value: State } | { type: 'counter.value'; value: number } type Context = { count: number } let runtime = createMachineRuntime({ initialState: 'idle', context: { count: 0 }, transition(context, state, event, runtime) { switch (event.type) { case 'counter.start': runtime.emit({ type: 'counter.state', value: 'running' }) return { state: 'running', effects: [{ type: 'counter.log', message: 'started' }] } case 'counter.increment': if (state !== 'running') return context.count += event.step ?? 1 runtime.emit({ type: 'counter.value', value: context.count }) return { effects: [{ type: 'counter.log', message: `count=${context.count}` }] } case 'counter.finish': runtime.emit({ type: 'counter.state', value: 'done' }) return { state: 'done', effects: [{ type: 'counter.log', message: 'finished' }] } } }, effects: { 'counter.log'(effect) { console.log('[effect]', effect.message) }, }, }) void (async () => { for await (let out of runtime) { console.log(out) } })() runtime.dispatch({ type: 'counter.start' }) runtime.dispatch({ type: 'counter.increment' }) runtime.dispatch({ type: 'counter.finish' }) await runtime.close('done') await runtime.destroy('finalized') ``` -------------------------------- ### Static Credentials Authentication Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/core.md Example of configuring the driver with static username and password credentials. ```typescript import { Driver } from '@ydbjs/core' import { StaticCredentialsProvider } from '@ydbjs/auth/static' const authEndpoint = 'grpcs://ydb.example.com:2135' // AuthService endpoint const driver = new Driver('grpcs://ydb.example.com:2135/your-db', { credentialsProvider: new StaticCredentialsProvider( { username: process.env.YDB_USER!, password: process.env.YDB_PASSWORD!, }, authEndpoint ), }) await driver.ready() ``` -------------------------------- ### Run All Examples Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/README.MD Commands to run all the provided examples. ```bash cd examples/api && npm start cd examples/query && npm run dev cd examples/drizzle-adapter && npm start cd examples/sls && npm start cd examples/tls && npm start cd examples/topic && npm start cd examples/coordination && npm start cd examples/fsm && npm start cd examples/telemetry && npm start cd examples/service-account && npm start ``` -------------------------------- ### Quick Start Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/third-parties/drizzle-adapter/README.md A quick start example demonstrating how to use the @ydbjs/drizzle-adapter to insert and select data. ```ts import { eq } from 'drizzle-orm' import { createDrizzle } from '@ydbjs/drizzle-adapter' import { integer, primaryKey, text, timestamp, uint64, ydbTable, } from '@ydbjs/drizzle-adapter/schema' import { currentUtcTimestamp, numericHash } from '@ydbjs/drizzle-adapter/sql' let users = ydbTable( 'users', { hash: uint64('hash').notNull(), id: integer('id').notNull(), email: text('email').notNull(), createdAt: timestamp('created_at').notNull(), }, (t) => [primaryKey(t.hash, t.id)] ) let db = createDrizzle({ connectionString: process.env['YDB_CONNECTION_STRING']!, schema: { users }, }) await db .insert(users) .values({ hash: numericHash(1), id: 1, email: 'ada@example.com', createdAt: currentUtcTimestamp(), }) .execute() let row = await db .select({ id: users.id, email: users.email }) .from(users) .where(eq(users.id, 1)) .prepare() .get() await db.$client.close?.() ``` -------------------------------- ### Quick Start Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/drizzle/index.md A quick start example demonstrating basic Drizzle operations with the YDB adapter, including schema definition, insertion, querying, and selection. ```typescript import { createDrizzle } from '@ydbjs/drizzle-adapter' import { integer, text, ydbTable } from '@ydbjs/drizzle-adapter/schema' import { eq } from 'drizzle-orm' export const users = ydbTable('users', { id: integer('id').primaryKey(), name: text('name').notNull(), }) const db = createDrizzle({ connectionString: process.env.YDB_CONNECTION_STRING!, schema: { users }, }) await db.insert(users).values({ id: 1, name: 'Alice' }).execute() const row = await db.query.users.findFirst({ where: (user, { eq }) => eq(user.id, 1), }) const selected = await db .select({ id: users.id, name: users.name }) .from(users) .where(eq(users.id, 1)) .prepare() .get() ``` -------------------------------- ### Access Token Authentication Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/core.md Example of configuring the driver with an Access Token credentials provider. ```typescript import { Driver } from '@ydbjs/core' import { AccessTokenCredentialsProvider } from '@ydbjs/auth/access-token' const driver = new Driver('grpcs://ydb.example.com:2135/your-db', { credentialsProvider: new AccessTokenCredentialsProvider({ token: process.env.YDB_TOKEN!, }), }) await driver.ready() ``` -------------------------------- ### Run with discovery enabled Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/diagnostics/README.md Start a local YDB container with discovery enabled and run the example. ```sh docker run -d --rm --name ydb-diag-demo --hostname localhost \ -p 2136:2136 ydbplatform/local-ydb:latest ENABLE_DISCOVERY=1 \ YDB_CONNECTION_STRING=grpc://localhost:2136/local \ npm start ``` -------------------------------- ### Quick start Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/coordination/index.md This example demonstrates how to create a coordination node, acquire an exclusive lock using a mutex, and perform work. ```typescript import { Driver } from '@ydbjs/core' import { CoordinationClient } from '@ydbjs/coordination' const driver = new Driver(process.env['YDB_CONNECTION_STRING']!) const client = new CoordinationClient(driver) // Create a coordination node once during provisioning await client.createNode('/local/my-app', {}) // Acquire an exclusive lock await using session = await client.createSession('/local/my-app', {}) await using lock = await session.mutex('job-lock').lock() await doWork(lock.signal) // lock.release() ← called automatically // session.close() ← called automatically ``` -------------------------------- ### Quick Start Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/query/index.md This is a basic example of how to use the @ydbjs/query client to execute a simple YQL query. ```typescript import { Driver } from '@ydbjs/core' import { query } from '@ydbjs/query' const driver = new Driver('grpc://localhost:2136/local') await driver.ready() const sql = query(driver) const rows = await sql`SELECT 1 + 1 AS sum` console.log(rows) ``` -------------------------------- ### YDB Local Docker Run Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/README.MD Command to start a local YDB instance using Docker. ```bash docker run -d --rm --name ydb-local -h localhost \ --platform linux/amd64 \ -p 2135:2135 -p 2136:2136 -p 8765:8765 -p 9092:9092 \ -e GRPC_TLS_PORT=2135 -e GRPC_PORT=2136 -e MON_PORT=8765 \ -e YDB_KAFKA_PROXY_PORT=9092 \ ydbplatform/local-ydb:latest ``` -------------------------------- ### Service Discovery — service-discovery.js Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/coordination/README.md Runs the service discovery example. ```bash npm run service-discovery ``` -------------------------------- ### Run the example Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/telemetry/README.md Command-line instructions to run the YDB OpenTelemetry example, with options for default and custom connection strings and OTLP endpoints. ```bash # Defaults to grpc://localhost:2136/local and OTLP http://localhost:4318. node index.js # Or point at a real collector / cluster: YDB_CONNECTION_STRING=grpcs://your.host:2135/?database=/ru/your/database \ OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.local:4318 \ node index.js ``` -------------------------------- ### Usage Examples Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/environ/README.md Demonstrates how to set environment variables for different authentication methods. ```bash # Anonymous (local YDB) YDB_CONNECTION_STRING=grpc://localhost:2136/local npm start ``` ```bash # Static credentials (on-premises) YDB_CONNECTION_STRING=grpcs://ydb.example.com:2135/mydb \ YDB_STATIC_CREDENTIALS_USER=admin \ YDB_STATIC_CREDENTIALS_PASSWORD=secret \ YDB_SSL_ROOT_CERTIFICATES_FILE=/path/to/ca.pem \ npm start ``` ```bash # Access token YDB_CONNECTION_STRING=grpcs://ydb.example.com:2135/mydb \ YDB_ACCESS_TOKEN_CREDENTIALS=my-token \ npm start ``` ```bash # Metadata (cloud VM) YDB_CONNECTION_STRING=grpcs://ydb.example.com:2135/mydb \ YDB_METADATA_CREDENTIALS=1 \ npm start ``` -------------------------------- ### Shared Configuration — shared-config.js Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/coordination/README.md Runs the shared configuration example. ```bash npm run shared-config ``` -------------------------------- ### Installation Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/auth/README.md Install the package using npm. ```sh npm install @ydbjs/auth ``` -------------------------------- ### Installation Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/core/README.md Install the @ydbjs/core package using npm. ```sh npm install @ydbjs/core ``` -------------------------------- ### Leader Election — election.js Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/coordination/README.md Runs the leader election example. ```bash npm run election ``` -------------------------------- ### YDB Connection String Environment Variable Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/README.MD Environment variable to set the YDB connection string for manual setup. ```bash export YDB_CONNECTION_STRING="grpc://localhost:2136/local" ``` -------------------------------- ### Example: Using a Service Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/api/README.md An example demonstrating how to use the DiscoveryService with nice-grpc to list endpoints. ```ts import { createClientFactory, createChannel } from 'nice-grpc' import { DiscoveryServiceDefinition } from '@ydbjs/api/discovery' const clientFactory = createClientFactory() const discoveryClient = clientFactory.create( DiscoveryServiceDefinition, createChannel('http://localhost:2136') ) async function listEndpoints() { const response = await discoveryClient.listEndpoints({ database: '/local' }) console.log(response) } listEndpoints().catch(console.error) ``` -------------------------------- ### Installation Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/coordination/README.md Install the @ydbjs/coordination package using npm. ```bash npm install @ydbjs/coordination ``` -------------------------------- ### Installation Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/value/README.md Install the package using npm. ```sh npm install @ydbjs/value ``` -------------------------------- ### Installation Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/api/README.md Install the @ydbjs/api package using npm. ```sh npm install @ydbjs/api ``` -------------------------------- ### Installation Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/topic/README.md Install the @ydbjs/topic package using npm. ```sh npm install @ydbjs/topic ``` -------------------------------- ### Installation Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/fsm/README.md Install the @ydbjs/fsm package using npm. ```sh npm install @ydbjs/fsm ``` -------------------------------- ### Distributed Mutex — mutex.js Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/coordination/README.md Runs the distributed mutex example. ```bash npm run mutex ``` -------------------------------- ### TLS/mTLS with StaticCredentialsProvider Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/core.md Example of using StaticCredentialsProvider with TLS/mTLS options for authentication against AuthService. ```typescript import { Driver } from '@ydbjs/core' import { StaticCredentialsProvider } from '@ydbjs/auth/static' import * as fs from 'node:fs' const authEndpoint = 'grpcs://ydb.example.com:2135' const driver = new Driver('grpcs://ydb.example.com:2135/your-db', { credentialsProvider: new StaticCredentialsProvider( { username: 'user', password: 'pass', }, authEndpoint, { ca: fs.readFileSync('/etc/ssl/custom/ca.pem'), cert: fs.readFileSync('/etc/ssl/custom/client.crt'), // for mTLS key: fs.readFileSync('/etc/ssl/custom/client.key'), // for mTLS } ), }) await driver.ready() ``` -------------------------------- ### Basic Example Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/core/README.md A basic example demonstrating how to initialize the driver, create a client for the Discovery service, list endpoints, and close the driver. ```ts import { Driver } from '@ydbjs/core' import { DiscoveryServiceDefinition } from '@ydbjs/api/discovery' const driver = new Driver('grpc://localhost:2136/local') await driver.ready() const discovery = driver.createClient(DiscoveryServiceDefinition) const endpoints = await discovery.listEndpoints({ database: '/local' }) console.log(endpoints) await driver.close() ``` -------------------------------- ### TLS with custom CA Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/core.md Example of configuring TLS with a custom Certificate Authority (CA) file. ```typescript import { Driver } from '@ydbjs/core' import * as fs from 'node:fs' const driver = new Driver('grpcs://ydb.example.com:2135/your-db', { secureOptions: { ca: fs.readFileSync('/etc/ssl/custom/ca.pem'), servername: 'ydb.example.com', // SNI if needed }, }) await driver.ready() ``` -------------------------------- ### Anonymous Authentication Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/core.md Example of configuring the driver for anonymous access, suitable for local or public databases. ```typescript import { Driver } from '@ydbjs/core' import { AnonymousCredentialsProvider } from '@ydbjs/auth/anonymous' const driver = new Driver('grpc://localhost:2136/local', { credentialsProvider: new AnonymousCredentialsProvider(), }) await driver.ready() ``` -------------------------------- ### Metadata Authentication Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/core.md Example of configuring the driver with metadata credentials, typically used in cloud environments. ```typescript import { Driver } from '@ydbjs/core' import { MetadataCredentialsProvider } from '@ydbjs/auth/metadata' const driver = new Driver(process.env.YDB_CONNECTION_STRING!, { credentialsProvider: new MetadataCredentialsProvider({ // endpoint?: 'http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token' }), }) await driver.ready() ``` -------------------------------- ### mTLS (client cert + key) Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/core.md Example of configuring mutual TLS (mTLS) with client certificates and keys. ```typescript import { Driver } from '@ydbjs/core' import * as fs from 'node:fs' const driver = new Driver('grpcs://ydb.example.com:2135/your-db', { secureOptions: { ca: fs.readFileSync('/etc/ssl/custom/ca.pem'), cert: fs.readFileSync('/etc/ssl/custom/client.crt'), key: fs.readFileSync('/etc/ssl/custom/client.key'), // passphrase?: '...', }, }) await driver.ready() ``` -------------------------------- ### Custom CredentialsProvider with AbortSignal Handling Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/core.md Example of a custom CredentialsProvider that correctly handles AbortSignal for network requests and timeouts. ```typescript class MyCredentialsProvider extends CredentialsProvider { #token: string | null = null async getToken(force = false, signal: AbortSignal = AbortSignal.timeout(10_000)) { if (!force && this.#token) return this.#token const abort = AbortSignal.any([signal, AbortSignal.timeout(15_000)]) const res = await fetch(this.#endpoint, { method: 'POST', body: '{}', signal: abort, }) if (!res.ok) throw new Error(`Auth failed: ${res.status}`) const { token } = await res.json() this.#token = token return token } } ``` -------------------------------- ### Custom CredentialsProvider Implementation Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/core.md Example of implementing a custom CredentialsProvider by extending the base class and overriding the getToken method. ```typescript import { CredentialsProvider } from '@ydbjs/auth' class MyCredentialsProvider extends CredentialsProvider { #token: string | null = null async getToken(force = false, signal?: AbortSignal): Promise { if (!force && this.#token) return this.#token const token = await fetchTokenSomehow(signal) this.#token = token return token } } const driver = new Driver(process.env.YDB_CONNECTION_STRING!, { credentialsProvider: new MyCredentialsProvider(), }) ``` -------------------------------- ### Resource Management with await using — resource-management.js Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/examples/coordination/README.md Runs the resource management example using await using. ```bash npm run resource-management ``` -------------------------------- ### Quick start Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/topic/index.md This code snippet demonstrates how to initialize the YDB driver and create a topic reader to consume messages. ```typescript import { Driver } from '@ydbjs/core' import { topic } from '@ydbjs/topic' const driver = new Driver(process.env['YDB_CONNECTION_STRING']!) await driver.ready() const t = topic(driver) await using reader = t.createReader({ topic: '/Root/my-topic', consumer: 'c1' }) for await (const batch of reader.read()) { await reader.commit(batch) } ``` -------------------------------- ### Execution Methods Examples Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/drizzle/database-api.md Examples of using execution methods like execute, all, get, and values with raw SQL and query builders. ```typescript import { sql } from 'drizzle-orm' await db.execute(sql`DELETE FROM users WHERE id = ${1}`) const rows = await db.all(sql`SELECT * FROM users`) const first = await db.get(sql`SELECT * FROM users LIMIT 1`) const values = await db.values<[number, string]>(sql`SELECT id, name FROM users`) const firstBuilt = await db.get(db.select({ id: users.id, name: users.name }).from(users).limit(1)) ``` -------------------------------- ### Partition session hooks Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/topic/index.md This example shows how to use partition session hooks to manage read offsets and observe session start/stop events. ```typescript await using reader = t.createReader({ topic: '/Root/metrics', consumer: 'svc-a', onPartitionSessionStart: async (session, committed, { start, end }) => { // shift readOffset to resume from the last committed return { readOffset: committed } }, onPartitionSessionStop: async (session, committed) => { console.log('partition closed', session.partitionSessionId, 'committed', committed) }, onCommittedOffset: (session, committed) => { // observe commits (useful with fire-and-forget commit()) console.log('committed', session.partitionSessionId, committed) }, }) ``` -------------------------------- ### Static Credentials (Manual Usage) Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/packages/auth/README.md Example of manually using the StaticCredentialsProvider to get a token. ```ts import { StaticCredentialsProvider } from '@ydbjs/auth/static' const provider = new StaticCredentialsProvider( { username: 'username', password: 'password', }, 'grpc://localhost:2136/local' ) const token = await provider.getToken() // The token can be used in custom gRPC calls if needed ``` -------------------------------- ### Open Session Example Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/coordination/index.md This example shows how to use `openSession` for long-running work, with automatic session recreation after expiry. ```typescript const ctrl = new AbortController() for await (const session of client.openSession( '/local/my-app', { recoveryWindow: 15_000 }, ctrl.signal )) { try { await doWork(session) } catch { if (session.signal.aborted) continue // session expired — retry throw error } break // exit after one successful cycle } ``` -------------------------------- ### Shutdown Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/drizzle/getting-started.md Close the adapter's owned client if it was created from a connection string. ```ts db.$client.close?.() ``` -------------------------------- ### Smoke Test Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/drizzle/getting-started.md Execute a simple SQL query to test the database connection. ```ts import { sql } from 'drizzle-orm' await db.execute(sql`SELECT 1`) ``` -------------------------------- ### Good Commit Message Examples Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/AGENTS.md Examples of effective commit messages. ```bash Add retry backoff strategy for transient errors - Implement exponential backoff with jitter - Add tests for retry behavior - Update documentation ``` ```bash Fix memory leak in connection pool - Close idle connections after timeout - Add connection lifecycle tests ``` -------------------------------- ### CRUD Operations Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/drizzle/getting-started.md Basic Create, Read, Update, and Delete operations using the Drizzle adapter. ```ts import { and, eq, like } from 'drizzle-orm' await db.insert(users).values({ id: 1, email: 'alice@example.com', name: 'Alice' }).execute() await db .insert(users) .values([ { id: 2, email: 'bob@example.com', name: 'Bob' }, { id: 3, email: 'charlie@example.com', name: 'Charlie' }, ]) .execute() await db .insert(users) .values({ id: 1, email: 'alice_new@example.com', name: 'Alice Updated' }) .onDuplicateKeyUpdate({ set: { name: 'Alice Updated' } }) .execute() const filteredUsers = await db .select({ userId: users.id, userName: users.name, }) .from(users) .where(and(eq(users.id, 1), like(users.email, '%@example.com'))) .execute() await db.update(users).set({ name: 'Alice Cooper' }).where(eq(users.id, 1)).execute() await db.delete(users).where(eq(users.id, 1)).execute() ``` -------------------------------- ### Parameters and AS_TABLE Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/query/index.md Example demonstrating how to use parameters with the AS_TABLE function to insert data. ```typescript const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, ] await sql`INSERT INTO users SELECT * FROM AS_TABLE(${users})` ``` -------------------------------- ### Essential Development Commands Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/AGENTS.md Lists key npm commands for building, testing, and linting the project. ```bash npm run build # Build all packages (Turbo) npm run test:uni # Unit tests (fast, no Docker) npm run test:int # Integration tests (requires Docker + YDB) npm run test:all # All tests (uni + int + e2e) npm run lint # Run oxlint ``` -------------------------------- ### Basic reader/commit Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/topic/examples.md Demonstrates how to create a topic reader, read batches of messages, and commit them. ```typescript import { topic } from '@ydbjs/topic' const t = topic(driver) await using reader = t.createReader({ topic: '/Root/my-topic', consumer: 'c1' }) for await (const batch of reader.read({ limit: 100, waitMs: 1000 })) { if (!batch.length) continue // processing await reader.commit(batch) } ``` -------------------------------- ### Transactions Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/drizzle/getting-started.md Perform database operations within a transaction, with options for access mode, isolation level, and idempotency. ```ts import { TransactionRollbackError } from 'drizzle-orm/errors' try { await db.transaction( async (tx) => { await tx.insert(users).values({ id: 4, email: 'delta@example.com' }).execute() const user = await tx.select().from(users).where(eq(users.id, 4)).execute() if (user.length === 0) { tx.rollback() } }, { accessMode: 'read write', isolationLevel: 'serializableReadWrite', idempotent: true, } ) } catch (error) { if (error instanceof TransactionRollbackError) { console.log('transaction was rolled back') } } ``` -------------------------------- ### Multiple sources and partition filters Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/topic/index.md This example demonstrates how to configure a topic reader to consume messages from multiple topics and filter by specific partition IDs. ```typescript await using reader = t.createReader({ topic: [{ path: '/Root/topic-a', partitionIds: [0n, 1n] }, { path: '/Root/topic-b' }], consumer: 'svc-a', }) for await (const batch of reader.read({ waitMs: 500 })) { // process messages from both topics, filtered partitions } ``` -------------------------------- ### Define a Schema Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/drizzle/getting-started.md Define a YDB table schema using adapter-specific builders. YDB tables require a primary key. ```ts import { integer, text, timestamp, ydbTable } from '@ydbjs/drizzle-adapter/schema' export const users = ydbTable('users', { id: integer('id').primaryKey(), email: text('email').notNull().unique(), name: text('name'), createdAt: timestamp('created_at') .notNull() .$defaultFn(() => new Date()), }) ``` -------------------------------- ### Connect using Existing SDK Driver Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/drizzle/getting-started.md Wrap an existing SDK Driver with YdbDriver when your application already owns the driver. ```ts import { Driver } from '@ydbjs/core' import { YdbDriver, createDrizzle } from '@ydbjs/drizzle-adapter' const driver = new Driver('grpc://localhost:2136/local') const db = createDrizzle({ client: new YdbDriver(driver), }) ``` -------------------------------- ### Custom codecs Source: https://github.com/ydb-platform/ydb-js-sdk/blob/main/docs/guide/topic/examples.md Illustrates how to implement and use custom codecs for topic messages, using GZIP as an example. ```typescript import { Codec } from '@ydbjs/api/topic' import * as zlib from 'node:zlib' const MyGzip = { codec: Codec.GZIP, compress: (p: Uint8Array) => zlib.gzipSync(p), decompress: (p: Uint8Array) => zlib.gunzipSync(p), } await using reader = t.createReader({ topic: '/Root/custom', consumer: 'c1', codecMap: new Map([[Codec.GZIP, MyGzip]]), }) ```