Search code examples
azureazure-cosmosdbazure-cosmosdb-sqlapi

Azure pre-triggers


My goal is when I create a new item, the trigger sets the age to 18 years old.

this is my trigger function :

function trigger(item) {
    // Check if the document has an "age" field
    console.log("started triggering");
    if (item && item.age !== undefined) {
        // Update the "age" field to 18
        item.age = 18;
        console.log("done");
    }
    // Continue with the operation (insert)
    return item;
}

When I create new item, the age doesn't change input :

{
      "id": "86",
      "name": "dhia",
      "age": 11
}

output :

{
    "id": "86",
    "name": "dhia",
    "age": 11
}

My goal is when I create a new item, the trigger sets the age to 18 years old.

I tried to set the name, the age, even a small change to see the trigger working because I'm learning and this is my first pre-trigger ever.

Check image!


Solution

  • My goal is when I create a new item, the trigger sets the age to 18 years old.

    As Gaurav Mantri explained in this SO thread, the triggers are not run automatically whenever a document is inserted. What you would need to do is specify the trigger that you want to run when you're creating the document.

    Below are the steps I followed:

    • An object is created by CosmosClient utilizing a connection string containing an Azure Cosmos DB account's login data.

    • The GetContainer function is used to get a reference to a particular container within the Cosmos DB account.

    • An anonymous type having the properties id, name, and age is used to define an object.

    • It generates an ItemRequestOptions object and sets the PreTriggers property of that object to a list with the pre-trigger name updateAge. This pre-trigger will be executed before creating the item.

    • CreateItemAsync method on the container is used to create the item asynchronously.

    • The item is the new document, null shows that the code doesn't specify a particular partition key, and requestOptions has the pre-trigger data.

    Pre-Trigger:

    function updateAge() {
      var context = getContext();
      var request = context.getRequest();
      var itemToCreate = request.getBody();
     
      itemToCreate.age = 18;
    
      request.setBody(itemToCreate);
    }
    
    • The request context and the object to be created are retrieved by updateAge().

    • It modifies the age property of the item to set it to 18.

    • Uses request.setBody(itemToCreate) to update the item's content with the modified age value.

    Below Is the code I tried with:

    public async Task CreateItemAsync()
    {
        try
        {
            var client = new CosmosClient("*****");
            var container = client.GetContainer("newData", "newCont");
    
            var item = new
            {
                id = "3",
                name = "Pavan Balaji",
                age = 30
            };
    
            var requestOptions = new ItemRequestOptions
            {
                PreTriggers = new List<string> { "updateAge" }
            };
    
            var response = await container.CreateItemAsync(item, null, requestOptions);
    
            Console.WriteLine($"Request Charge: {response.RequestCharge}");
        }
        catch (CosmosException ex)
        {
            Console.WriteLine($"Cosmos DB Exception: {ex.Message}");
        }
    }
    
    static async Task Main(string[] args)
    {
        ClassName Instance = new ClassName();
        await Instance.CreateItemAsync();
    }
    

    Output:

    {
        "id": "3",
        "name": "Pavan Balaji",
        "age": 18
    }