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!