learning_ai_common_plat/packages/cosmos/src/client.ts
saravanakumardb1 2e9dcf49a8 feat(cosmos): add @bytelyst/cosmos package
- Singleton CosmosClient with env var config (COSMOS_ENDPOINT, COSMOS_KEY, COSMOS_DATABASE)
- Simple getContainer() for services
- Container registry with registerContainers(), getRegisteredContainer(), initializeAllContainers() for dashboards
- ContainerConfig type with partitionKeyPath and optional defaultTtl
- _resetClient() and _resetRegistry() for test isolation
- Peer dep: @azure/cosmos >=4.0.0
2026-02-12 11:19:42 -08:00

55 lines
1.3 KiB
TypeScript

/**
* Azure Cosmos DB client singleton.
*
* Reads COSMOS_ENDPOINT, COSMOS_KEY, and COSMOS_DATABASE from process.env.
* Provides getCosmosClient(), getDatabase(), and getContainer() for simple usage.
*/
import { CosmosClient, Database, Container } from "@azure/cosmos";
let _client: CosmosClient | null = null;
let _database: Database | null = null;
function getEnvOrThrow(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Environment variable ${name} is required`);
}
return value;
}
export function getCosmosClient(): CosmosClient {
if (!_client) {
_client = new CosmosClient({
endpoint: getEnvOrThrow("COSMOS_ENDPOINT"),
key: getEnvOrThrow("COSMOS_KEY"),
});
}
return _client;
}
export function getDatabase(): Database {
if (!_database) {
const dbId = process.env.COSMOS_DATABASE || "lysnrai";
_database = getCosmosClient().database(dbId);
}
return _database;
}
/**
* Get a container by name. Uses the singleton database.
* For simple services that don't need a container registry.
*/
export function getContainer(name: string): Container {
return getDatabase().container(name);
}
/**
* Reset the singleton (useful for testing).
* @internal
*/
export function _resetClient(): void {
_client = null;
_database = null;
}