lambdadb
Developer-friendly & type-safe Typescript SDK specifically catered to leverage LambdaDB API.
Summary
LambdaDB API: LambdaDB Open API Spec
Table of Contents
SDK Installation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add @functional-systems/lambdadb
PNPM
pnpm add @functional-systems/lambdadb
Bun
bun add @functional-systems/lambdadb
Yarn
yarn add @functional-systems/lambdadb
[!NOTE] This package is published with CommonJS and ES Modules (ESM) support.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
We recommend the collection-scoped client (LambdaDBClient): you get a handle for a collection once and then call methods without passing collectionName on every request.
Recommended: LambdaDBClient (collection-scoped)
The client connects to {baseUrl}/projects/{projectName}. Defaults: baseUrl https://api.lambdadb.ai, projectName playground. Override with baseUrl and projectName when creating the client.
import { LambdaDBClient } from "@functional-systems/lambdadb";
const client = new LambdaDBClient({
projectApiKey: "<YOUR_PROJECT_API_KEY>",
// Optional: baseUrl (default "https://api.lambdadb.ai"), projectName (default "playground")
});
async function run() {
// List all collections in the project (optional: pass { size, pageToken } for pagination)
const list = await client.listCollections();
console.log(list); // list.collections[].createdAt etc. are Date
// Work with a specific collection — no collectionName in every call
const collection = client.collection("my-collection");
await collection.get();
await collection.docs.list({ size: 20 });
await collection.docs.upsert({ docs: [{ id: "1", text: "hello" }] });
// For large document sets (up to 200MB), use bulkUpsertDocs for a single-call flow.
// Native embedding fields require caller-supplied vectors; bulk upsert never generates embeddings.
// await collection.docs.bulkUpsertDocs({ docs: largeDocArray });
}
run();
TypeScript types
Import request and response types from the package for type-safe usage. Use the input types for method arguments and the response types for return values.
import {
LambdaDBClient,
type CreateCollectionInput,
type QueryCollectionInput,
type QueryCollectionResponse,
type ListDocsInput,
type ListDocsResponse,
} from "@functional-systems/lambdadb";
const client = new LambdaDBClient({ projectApiKey: "..." });
const collection = client.collection("my-collection");
// Typed list params
const params: ListDocsInput = { size: 20, pageToken: undefined };
const listResult: ListDocsResponse = await collection.docs.list(params);
// Typed query body and response (or use createQueryInput helper)
const queryBody: QueryCollectionInput = {
query: { text: "hello" },
size: 10,
};
const queryResult: QueryCollectionResponse = await collection.query(queryBody);
Common types: CreateCollectionInput, UpdateCollectionInput, QueryCollectionInput, ListDocsInput, ListCollectionsInput, UpsertDocsInput, DeleteDocsInput, FetchDocsInput, BulkUpsertInput; response types such as QueryCollectionResponse, ListDocsResponse, ListCollectionsResponseWithDates, GetCollectionResponseWithDates, FetchDocsResponse, MessageResponse; Data Versioning types such as ReadRef, BranchSource, RefSource, AliasTarget, SnapshotDetails, ParentBranchDetails, BranchDetails, and TagDetails; and model types like CollectionResponseWithDates, IndexConfigsUnion, IndexConfigsManagedEmbeddingVector, EmbeddingConfig, PartitionConfig, FieldsSelectorUnion. Collection create/list/get/update and ref lifecycle responses expose timestamps as Date. All are exported from the main package.
Data Versioning
Create Collection-scoped Branches, Tags, and Aliases, then select a ref for reads or a Branch for writes:
import {
LambdaDBClient,
aliasRef,
branchSource,
tagTarget,
} from "@functional-systems/lambdadb";
const client = new LambdaDBClient({ projectApiKey: "..." });
const collection = client.collection("knowledge-base");
await collection.branches.create({
branchName: "candidate",
source: branchSource("main"),
});
await collection.tags.create({
tagName: "release-001",
source: branchSource("candidate"),
});
await collection.aliases.create({
aliasName: "production",
target: tagTarget("release-001"),
});
await collection.docs.upsert({
branch: "candidate",
docs: [{ id: "doc-1", text: "candidate content" }],
});
for await (const page of collection.docs.listPages({
size: 50,
ref: aliasRef("production"),
})) {
console.log(page.docs);
}
Omitting a read ref or write Branch preserves the existing main behavior.
Branch creation accepts only Branch sources; omitting source selects main,
and branchSource(name, asOf) supports point-in-time creation. Tag creation
continues to accept Branch or Tag sources. Branch create/list responses include
required nullable parentBranch: { branchId, name }, even for an empty head;
main and Branches without recorded parents return null.
See Data Versioning for lifecycle methods, safe
errors, point-in-time Branch sources, signed bulk uploads, and transfer-client
configuration. The Data Versioning contract is pinned at lambdadb/docs commit
1714009a2659a18b26cb68193dd7a071fd6efb42 (reference/api/openapi.json), which also allows
consistentRead: true through an Alias that targets a Branch. Deleting a Branch or Tag referenced
by an Alias fails with CatalogConflictError (HTTP 409); delete or retarget
all referencing Aliases first. Reads through an Alias whose
target is dangling fail with BadRequestError (HTTP 400), while selecting a
ref that does not exist fails with ResourceNotFoundError (HTTP 404).
The 49 fixed text analyzer presets are documented in Analyzer and use a separate pinned source contract.
Index field descriptions
Every index field, including nested object children, accepts an optional
description of up to 255 characters. It never affects indexing and is returned
by Collection reads only when set. On update, omitting it keeps the stored
description, "" clears it, and a new value replaces it; it is the only setting
of an existing field that an update may change. The server-managed id field
does not accept one. See IndexConfigsUnion.
await client.createCollection({
collectionName: "books",
indexConfigs: {
title: { type: "text", analyzers: ["english"], description: "Book title as printed on the cover" },
details: {
type: "object",
objectIndexConfigs: { pages: { type: "long", description: "Page count" } },
},
},
});
Query limits
Query size, dense knn.k, Bayesian candidateSize, and
rerank.candidateSize support up to 1000 on the
pinned backend contract.
Query results and hydrated candidate bodies no longer have an aggregate 64 MiB
limit. Large results use the existing docsUrl download format; exhaustion of
the server's shared temporary storage budget returns HTTP 503 without partial results.
See query size and byte limits.
Facet buckets retain their 100-item limit. Fetch and GET/POST List support up to
1000 IDs/documents; List defaults to 100. Fetch retains a 64 MiB per-node JSON
budget. See the read contract.
Source alignment does not establish deployment to your endpoint.
Native reranking
Pass an optional per-query rerank object to query or querySafe with
provider: "typesafe" and model: "jev-1.13.0", or provider: "cohere" and
model: "rerank-v5.0-pro" / "rerank-v5.0-fast", plus nonblank queryText
and stored scalar text fields. The server manages credentials. For TypeSafe,
optional criteria selects 2–10 ordered custom descriptions; omission/null uses
the default criteria. Cohere does not accept criteria.
See Native reranking for default/custom/Cohere examples,
candidate limits, response fields and eligible fallback behavior. An applied
score is the final evaluation score in [0,1], not a relevance probability;
retrievalScore retains the original search score outside doc. Inspect
rerank.status because fallback retains search scores. Omitted/null rerank
keeps existing query behavior.
Keyword facets
Count matching documents by indexed keyword values, including arrays and dotted
field paths. Query-level size: 0 returns counts without documents; omit query
to count all documents in the selected read scope.
const result = await client.collection("items").query({
size: 0,
facets: { tags: { size: 5 } },
});
for (const bucket of result.facets?.tags?.buckets ?? []) {
console.log(bucket.value, bucket.count);
}
querySafe accepts the same input. Request up to five keyword fields, with
1–100 buckets per field (default 10 when omitted or null). Counts cover all
matching documents, independent of the number of documents returned, and survive
docsUrl downloads. Public types include FacetRequest, FacetBucket, and
FacetResult.
Use a server deployment containing the facet feature and newly built keyword indexes. Existing data must be reinserted into a new Collection; old Tags and partial index updates do not migrate the format. See keyword facets for supported queries, limits, and validation evidence.
Pagination
Documents: Use listPages() to iterate over all pages without loading everything into memory, or listAll() to fetch all docs into a single list. Each page is one API response; the API limits response size by payload, not by document count, so the number of docs per page may be less than the requested size and can vary from page to page. The methods list(), query(), and fetch() automatically resolve documents from the presigned URL when the API returns them via docsUrl (isDocsInline: false), so you always receive docs in the response.
Page tokens are opaque search positions, not Snapshot pins. For a stable multi-page export, select the same immutable Tag and keep filters and field selection unchanged on every page.
import { LambdaDBClient } from "@functional-systems/lambdadb";
const client = new LambdaDBClient({ projectApiKey: "..." });
const collection = client.collection("my-collection");
// Page-by-page (memory efficient)
for await (const page of collection.docs.listPages({ size: 50 })) {
console.log(page.docs.length, page.nextPageToken ?? "last page");
}
// Or load all docs (for small/medium collections)
const { docs, total } = await collection.docs.listAll({ size: 100 });
console.log(docs.length, total);
Collections: Use listCollections(params?) with optional size and pageToken, or listCollectionsPages(params?) / listAllCollections(params?) to iterate or fetch all collections across pages.
// One page
const page = await client.listCollections({ size: 20 });
// Page-by-page
for await (const page of client.listCollectionsPages({ size: 20 })) {
console.log(page.collections.length, page.nextPageToken ?? "last");
}
// All collections
const { collections } = await client.listAllCollections({ size: 50 });
Query helper
Use createQueryInput() to build query parameters for collection.query() or collection.querySafe():
import { LambdaDBClient, createQueryInput } from "@functional-systems/lambdadb";
const client = new LambdaDBClient({ projectApiKey: "..." });
const collection = client.collection("my-collection");
const input = createQueryInput({ text: "hello" }, { size: 10 });
const result = await collection.query(input);
Qdrant Compatibility
For common Qdrant JavaScript client migration paths, use the explicit Qdrant-style compatibility adapter:
import { QdrantCompatClient, models } from "@functional-systems/lambdadb/compat/qdrant";
const client = new QdrantCompatClient({
projectApiKey: "<YOUR_PROJECT_API_KEY>",
projectName: "playground",
});
await client.createCollection("docs", {
vectorsConfig: new models.VectorParams({
size: 64,
distance: models.Distance.COSINE,
}),
});
The adapter covers the common dense-vector RAG subset and is not a full Qdrant client replacement. See docs/compatibility/qdrant.md for supported methods, data mapping, and unsupported features.
Live Qdrant compatibility smoke tests can load credentials from a local .env
file:
cp .env.example .env
# Fill in LAMBDADB_PROJECT_API_KEY and set LAMBDADB_RUN_LIVE_TESTS=1.
npm run test:live:qdrant
External integration smoke tests for LangChain JS and LlamaIndex TS use an in-process fake LambdaDB transport and do not require credentials:
npm run test:external:qdrant
Native embeddings
Native embedding vector fields generate vectors from configured stored JSON
paths. The sources and their object ancestors need no index declarations. Declare
the vector field, write the original JSON, and query with knn.queryText:
import { LambdaDBClient } from "@functional-systems/lambdadb";
const client = new LambdaDBClient({ projectApiKey: "..." });
await client.createCollection({
collectionName: "semantic-items",
indexConfigs: {
bodyEmbedding: {
type: "vector",
embedding: {
provider: "openai",
model: "text-embedding-3-small",
sources: [{ field: "article.body", type: "text" }],
},
},
},
});
const collection = client.collection("semantic-items");
await collection.docs.upsert({
docs: [{ id: "policy-1", article: { body: "Refunds are available within 30 days." } }],
});
const result = await collection.query({
size: 10,
query: {
knn: {
field: "bodyEmbedding",
queryText: "refund policy",
k: 10,
},
},
});
The legacy sourceField: "article.body" form remains supported. Cohere
(embed-v5.0-pro / embed-v5.0-fast) also accepts ordered text and image
sources and mixed knn.queryInputs; see
ordered and image sources.
rerank.fields can select the same unindexed string path. Add appropriate source
indexes when you also need lexical search, filtering, or sorting on those fields.
This requires the pinned native embedding contract
at the deployed endpoint; a legacy flag alone does not enable unindexed sources.
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
|---|---|---|---|
projectApiKey | apiKey | API key | LAMBDADB_PROJECT_API_KEY |
To authenticate with the API the projectApiKey parameter must be set when initializing the SDK client instance. For example:
import { LambdaDBClient } from "@functional-systems/lambdadb";
const client = new LambdaDBClient({
projectApiKey: "<YOUR_PROJECT_API_KEY>",
});
async function run() {
const result = await client.listCollections();
console.log(result);
}
run();
Available Resources and Operations
Available methods
Collections
- list - List all collections in an existing project (supports pagination:
size,pageToken). On LambdaDBClient uselistCollections(params?),listCollectionsPages(params?), orlistAllCollections(params?)for iteration; collection responses includecreatedAt/updatedAt/dataUpdatedAtasDate. - create - Create a collection.
- delete - Delete an existing collection.
- get - Get metadata of an existing collection.
- update - Configure a collection.
- query - Search a collection with a query and return the most similar documents.
Collections.Docs
- listDocs - List documents in a collection.
- upsert - Upsert documents into a collection. Note that the maximum supported payload size is 6MB.
- bulkUpsertDocs - Bulk upsert documents in one call (up to 200MB); use this for best DX when you have a document list. Native embedding fields require caller-supplied vectors; bulk upsert never generates embeddings.
- getBulkUpsert - Request required info to upload documents. Native embedding fields require caller-supplied vectors; bulk upsert never generates embeddings.
- bulkUpsert - Bulk upsert documents into a collection. Note that the maximum supported object size is 200MB. Native embedding fields require caller-supplied vectors; bulk upsert never generates embeddings.
- update - Update documents in a collection. Note that the maximum supported payload size is 6MB.
- delete - Delete documents by exactly one of document IDs or query filter.
- fetch - Lookup and return documents by document IDs from a collection.
Legacy API (LambdaDB)
The classic client LambdaDB is still supported for compatibility. New code should prefer LambdaDBClient and client.collection(name).
import { LambdaDB } from "@functional-systems/lambdadb";
const lambdaDB = new LambdaDB({ projectApiKey: "<YOUR_PROJECT_API_KEY>" });
const result = await lambdaDB.collections.list();
await lambdaDB.collections.docs.listDocs({ collectionName: "my-collection", size: 20 });
See docs/sdks/collections/README.md and docs/sdks/docs/README.md for the full legacy API reference.
Standalone functions
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
Available standalone functions
collectionsCreate- Create a collection.collectionsDelete- Delete an existing collection.collectionsDocsBulkUpsert- Bulk upsert documents into a collection. Note that the maximum supported object size is 200MB. Native embedding fields require caller-supplied vectors; bulk upsert never generates embeddings.collectionsDocsDelete- Delete documents by exactly one of document IDs or query filter.collectionsDocsFetch- Lookup and return documents by document IDs from a collection.collectionsDocsGetBulkUpsert- Request required info to upload documents. Native embedding fields require caller-supplied vectors; bulk upsert never generates embeddings.collectionsDocsListDocs- List documents in a collection.collectionsDocsUpdate- Update documents in a collection. Note that the maximum supported payload size is 6MB.collectionsDocsUpsert- Upsert documents into a collection. Note that the maximum supported payload size is 6MB.collectionsGet- Get metadata of an existing collection.collectionsList- List all collections in an existing project.collectionsQuery- Search a collection with a query and return the most similar documents.collectionsUpdate- Configure a collection.
Retries
Retry behavior is configured by the SDK. Document write API requests use backoff
retries by default for HTTP 429, all 5xx responses (including 500, 502, 503, and
504), and connection errors or transport timeouts. Per-call retries overrides
the client's retryConfig. The same retry settings apply to *Safe methods;
returning a Result does not disable retries.
For retryable 429 responses, the backoff implementation honors a valid
Retry-After header when present. The API does not guarantee that every 429
contains this header.
For writes, an error does not prove that the mutation was not committed. The response can be lost after a successful commit, and automatic retries can reapply the write before the SDK returns an error or a successful response. Retries do not provide exactly-once execution.
To inspect state before deciding whether to retry a write, disable automatic retries on the initial call:
import { LambdaDBClient } from "@functional-systems/lambdadb";
const client = new LambdaDBClient({
projectApiKey: "<YOUR_PROJECT_API_KEY>",
});
const collection = client.collection("my-collection");
await collection.docs.upsert(
{ docs: [{ id: "doc-1", title: "Updated title" }] },
{ retries: { strategy: "none" } },
);
This disables both HTTP-status and connection-error retries for that call.
Setting only retryConnectionErrors: false still allows retryable HTTP
responses, including 502 and 504, to be retried. Disabling retries does not
cancel a server-side write or establish its outcome. After a failure, inspect
the target Branch state and consider the operation's semantics before issuing
another write. The SDK does not perform that reconciliation automatically.
To change the retry strategy for a single API call, pass retries in its request options:
import { LambdaDBClient } from "@functional-systems/lambdadb";
const client = new LambdaDBClient({
projectApiKey: "<YOUR_PROJECT_API_KEY>",
});
async function run() {
const result = await client.listCollections(undefined, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { LambdaDBClient } from "@functional-systems/lambdadb";
const client = new LambdaDBClient({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
projectApiKey: "<YOUR_PROJECT_API_KEY>",
});
async function run() {
const result = await client.listCollections();
console.log(result);
}
run();
Timeout and request-level options: You can set a request timeout (ms) and retry behavior when creating the client or per call. If not set, there is no request timeout. The RetryConfig type is exported from the package for typing your options.
import { LambdaDBClient, type RetryConfig } from "@functional-systems/lambdadb";
const client = new LambdaDBClient({
projectApiKey: "...",
timeoutMs: 30_000, // 30s timeout for all requests
retryConfig: { strategy: "backoff", retryConnectionErrors: true },
});
// Override per request
await client.listCollections(undefined, { timeoutMs: 10_000, retries: { strategy: "none" } });
Error Handling
LambdaDBError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
|---|---|---|
error.message | string | Error message |
error.statusCode | number | HTTP response status code eg 404 |
error.headers | Headers | HTTP response headers |
error.body | string | HTTP body. Can be empty string if no body is returned. |
error.rawResponse | Response | Raw HTTP response |
error.retryAfter | string | undefined | Optional Retry-After response header. |
error.data$ | Optional. Some errors may contain structured data. See Error Classes. |
Default methods (throw on error)
Regular methods throw on failure. Catch errors and use instanceof to narrow types. Error classes are exported from the main package:
import {
LambdaDBClient,
LambdaDBError,
UnauthenticatedError,
ResourceNotFoundError,
} from "@functional-systems/lambdadb";
const client = new LambdaDBClient({
projectApiKey: "<YOUR_PROJECT_API_KEY>",
});
async function run() {
try {
const result = await client.listCollections();
console.log(result);
} catch (error) {
if (error instanceof LambdaDBError) {
console.log(error.message, error.statusCode, error.body);
if (error instanceof UnauthenticatedError) {
console.log(error.data$.message);
}
if (error instanceof ResourceNotFoundError) {
console.log("Not found:", error.data$);
}
}
}
}
run();
Safe methods (return Result)
Use *Safe methods to get a Result<T, E> instead of throwing. You can handle errors without try/catch and narrow with type guards:
import {
LambdaDBClient,
Result,
ResourceNotFoundError,
} from "@functional-systems/lambdadb";
const client = new LambdaDBClient({ projectApiKey: "..." });
const result = await client.listCollectionsSafe();
if (result.ok) {
console.log(result.value.collections);
} else {
const err = result.error;
if (err instanceof ResourceNotFoundError) {
console.log("Not found:", err.data$);
} else {
console.error(err);
}
}
Available Safe methods: listCollectionsSafe, createCollectionSafe, collection.getSafe, collection.updateSafe, collection.deleteSafe, collection.querySafe, collection.docs.listSafe, collection.docs.upsertSafe, collection.docs.updateSafe, collection.docs.deleteSafe, collection.docs.fetchSafe, collection.docs.getBulkUpsertSafe, collection.docs.bulkUpsertSafe, collection.docs.bulkUpsertDocsSafe. The Result type and OK / ERR helpers are exported from the package.
Data Versioning lifecycle handles also provide createSafe, listSafe,
deleteSafe, and aliases.retargetSafe.
Error Classes
Primary errors:
LambdaDBError: The base class for HTTP error responses.UnauthenticatedError: Unauthenticated. Status code401.TooManyRequestsError: Too many requests. Status code429.InternalServerError: Internal server error. Status code500.ResourceNotFoundError: Resource not found. Status code404. *CatalogConflictError: Conditional catalog conflict. Status code409.PayloadTooLargeError: Gateway request limit exceeded. Status code413.BadGatewayError: Unexpected downstream failure. Status code502.ServiceUnavailableError: Transient dependency failure. Status code503.GatewayTimeoutError: Gateway deadline exceeded. Status code504.
Less common errors (8)
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from LambdaDBError:
BadRequestError: Bad request. Status code400. Applicable to 10 of 13 methods.*ResourceAlreadyExistsError: Resource already exists. Status code409. Applicable to 1 of 13 methods.*ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
* Check the method documentation to see if the error is applicable.
Server Selection (API base URL)
LambdaDBClient builds the API base as {baseUrl}/projects/{projectName}. You can override the defaults when creating the client.
| Option | Type | Default | Description |
|---|---|---|---|
baseUrl | string | "https://api.lambdadb.ai" | API base URL (no trailing slash). |
projectName | string | "playground" | Project name (path segment). |
serverURL | string | — | Full base URL (overrides baseUrl + projectName). |
projectHost | string | — | Legacy: host path for URL (e.g. api.lambdadb.ai/projects/my-project). |
Using baseUrl and projectName (recommended)
import { LambdaDBClient } from "@functional-systems/lambdadb";
const client = new LambdaDBClient({
projectApiKey: "<YOUR_PROJECT_API_KEY>",
baseUrl: "https://api.lambdadb.ai",
projectName: "my-project",
});
const result = await client.listCollections();
Override with full server URL
To set the base URL in one go, use serverURL:
import { LambdaDBClient } from "@functional-systems/lambdadb";
const client = new LambdaDBClient({
serverURL: "https://api.lambdadb.ai/projects/my-project",
projectApiKey: "<YOUR_PROJECT_API_KEY>",
});
const result = await client.listCollections();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to use the "beforeRequest" hook to add a
custom header and a timeout to requests and how to use the "requestError" hook
to log errors:
import { LambdaDBClient } from "@functional-systems/lambdadb";
import { HTTPClient } from "@functional-systems/lambdadb/lib/http";
const httpClient = new HTTPClient({
// fetcher takes a function that has the same signature as native `fetch`.
fetcher: (request) => {
return fetch(request);
}
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const client = new LambdaDBClient({ httpClient, projectApiKey: "<YOUR_PROJECT_API_KEY>" });
Pass a separate transferClient for presigned uploads and out-of-line result
downloads. API authentication and API-only headers are never copied to this
transport. Per-call signal and timeoutMs still apply to transfer requests.
Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { LambdaDBClient } from "@functional-systems/lambdadb";
const client = new LambdaDBClient({ debugLogger: console, projectApiKey: "<YOUR_PROJECT_API_KEY>" });
You can also enable a default debug logger by setting an environment variable LAMBDADB_DEBUG to true or 1 (case-insensitive). Any other value, including false and 0, leaves it disabled.
Development
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version unless you are intentionally looking for the latest version.
Contributions
We welcome contributions. The recommended API is implemented in src/client.ts (LambdaDBClient, collection-scoped). The rest of src/ (funcs, models, lib) is maintained manually; see docs/OPENAPI_UPDATE.md for how API changes are applied. Feel free to open a PR or an issue.