Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

477
Vistas
How to initialize cosmosDB databases and containers in azure functions using the node sdk?

In my current implementation I have database initialization code that gets run on every function request, which is bad for performance reasons.

How to check if a container exists in cosmos DB using the node sdk?

It's best to create static connections on app initialization as described here: https://docs.microsoft.com/en-us/azure/azure-functions/manage-connections#static-clients

but I'm having a bit of trouble with the initialization. Here is how the documentation describes it in javascript.

const cosmos = require('@azure/cosmos');
const endpoint = process.env.COSMOS_API_URL;
const key = process.env.COSMOS_API_KEY;
const { CosmosClient } = cosmos;

const client = new CosmosClient({ endpoint, key });
// All function invocations also reference the same database and container.
const container = client.database("MyDatabaseName").container("MyContainerName");

module.exports = async function (context) {
    const { resources: itemArray } = await container.items.readAll().fetchAll();
    context.log(itemArray);
}

The issues/questions I'm having are how do I do error handling if the database does not exist or if the container does not exist.

Do I need to separate my "createIfNotExists" logic from the functions app entirely?

If I try to run the createIfNotExists code on startup, I'm not able to do top level awaits and I have been getting promise rejections errors.

I'd like to do something like the following:

try
{
  const cosmos = require('@azure/cosmos');
  const endpoint = process.env.COSMOS_API_URL;
  const key = process.env.COSMOS_API_KEY;
  const { CosmosClient } = cosmos;

  const client = new CosmosClient({ endpoint, key });
  const db = await client.databases.createIfNotExists({id: "databaseId"});
  const container1 = await db.container.createIfNotExists(containerDefinition1)
  const container2 = await db.container.createIfNotExists(containerDefinition2)
}
catch(err)
{
  handleError(err)
}

...

module.exports = async function (context) {
    ...
    const {resources: items } = await container1.items.query(querySpec).fetchAll();
}


What's the best way to implement this? Any help is appreciated!

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I think you need to handle each individually, for example

  async onApplicationLoad() {
        // Create DB if it doesn't exist
        try {
            await this.client.databases.createIfNotExists({ id: this.mDBId });
        } catch (error) {
            Logger.log(`Error creating database: ${error}`, 'AzureCosmosDbService');
        }
  
        // Create the containers if they don't exist
        try {
            await this.client.database(this.mDBId).containers.createIfNotExists({ id: this.mNoteContainerId });
            await this.client.database(this.mDBId).containers.createIfNotExists({ id: this.mReportedNotesContainerId });
  
            const iterator = this.client.database(this.mDBId).containers.readAll();
            const { resources: containersList } = await iterator.fetchAll();
        } catch (error) {
            Logger.log(`Error creating containers: ${error}`, 'AzureCosmosDbService');
        }
        return;
      }
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda