skip to Main Content

I’m learning Azure functions and have faced a problem.
The function hangs when getting a record from cosmos db.
I use the cosmos db emulator.
The function works properly without code that fetches records from cosmos db. I see log: First id value is: 3.

const { app } = require('@azure/functions');

app.http('httpTrigger', {
    methods: ['GET', 'POST'],
    handler: async (request, context) => {
        try {
        const Id = request.query.get('id');

        context.log(`First id value is: ${Id}`);

        return {body: `Response id =${Id}`};

    } catch (error) {
        context.log(`Error: ${error}`);
        return { status: 500, body: 'Internal Server Error' };
      }
    }
});

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "AzureWebJobsFeatureFlags": "EnableWorkerIndexing",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "CosmosDBConnectionString":"AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="
  }
}

But the function doesn’t work properly with the code that fetches records from cosmos db. I don’t see logs. It looks like the function was triggered but the code (logs) inside the handler was not executed.

const { app, input } = require('@azure/functions');

const cosmosInput = input.cosmosDB({
    
    databaseName: 'my-database',
    containerName: 'my-container',
    connection: 'CosmosDBConnectionString',
    sqlQuery: 'SELECT * FROM c'
});

app.http('httpTrigger', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    extraInputs: [cosmosInput],
    handler: async (request, context) => {
        try {
        const Id = request.query.get('id');

        context.log(`First id value is: ${Id}`);

        const toDoItem = context.extraInputs.get(cosmosInput);

        context.log(`Second id value is: ${Id}`);

        return {body: `Response id =${Id}`};

    } catch (error) {
        context.log(`Error: ${error}`);
        return { status: 500, body: 'Internal Server Error' };
      }
    }
});

I try to get records from cosmos db in an Azure function.

2

Answers


  1. I try to get records from cosmos db in an Azure function.

    Try with the below code to retrieve data from Azure Cosmos DB Emulator using JavaScript functions v4.

    const { app } = require('@azure/functions');
    const { CosmosClient } = require("@azure/cosmos");
    
    const cosmosClient = new CosmosClient({ endpoint, key });
    
    app.http('httpTrigger1', {
        methods: ['GET'],
        authLevel: 'anonymous',
        handler: async (request, context) => {
            context.log(`Http function processed request for url "${request.url}"`);
    
            try {
                const database = cosmosClient.database(databaseId);
                const container = database.container(containerId);
    
                const querySpec = {
                    query: "SELECT * FROM c"
                };
    
                const { resources: items } = await container.items.query(querySpec).fetchAll();
                
                return {
                    body: JSON.stringify(items) // Stringify the items array
                };
            } catch (error) {
                context.log.error("Error retrieving data from Cosmos DB:", error);
                return {
                    status: 500,
                    body: "Internal Server Error"
                };
            }
        }
    });
    

    Output:
    enter image description here

    [{"id":"1","name":"Sai","dept":"IT"},{"id":"2","name":"Pavan","dept":"Non-IT"},{"id":"3","name":"Venky","dept":"Hardware"}]
    
    Login or Signup to reply.
  2. First, start by verifying the Azure Functions logs, the query might be failing with authentication or connectivity issues. When working with the Emulator, there might be authentication issues (like missing certificates) that would make the Input binding fail in the background.

    Secondly, SELECT * FROM c you are reading the entire Container every time you execute the Function, there is no filtering.
    This is a cross-partition query that can the more data the Container has, the longer the Function will take and the more RUs which increases the changes of throttling.

    The intent of the Function is unclear, maybe the query should be filtered by the input? Like SELECT * FROM c WHERE c.id = '{id}'?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search