Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger in CosmosDB not fired?

I have created a simple Pre Trigger in my CosmosDB collection.

function testTrigger() {
    var context = getContext();
    var request = context.getRequest();
    var documentToCreate = request.getBody();
    documentToCreate["test"] = "Added by trigger";
    request.setBody(documentToCreate);
}

Though it seems, this trigger isn't fired at all.

What's also irritating, the getContext() call is marked with a green squiggly line in the script explorer.

enter image description here

like image 443
Thomas Mutzl Avatar asked Dec 05 '22 02:12

Thomas Mutzl


1 Answers

The problem that the trigger doesn't seem to be... well... triggered, is that you aren't specifying it on the triggering operation. Triggers are not automatic. They must be specified for each database operation where you want them executed.

Personally, I think that was a unfortunate design choice and I've decided to not use triggers at all in my own code. Rather, I embed all the business rule constraints in stored procedures. I find this to be a bit cleaner and removes the worry that I'll forget to specify a trigger or (more likely) someone else writing code to the database won't even know that they should. I realize that someone can bypass my stored procedure and violate the business rules by going directly to the documents, but I don't know of any way in DocumentDB to protect against that. If there was a way to make triggers be automatic, that would have protected against that.

When using the REST API, you specify triggers in a header with x-ms-documentdb-pre-trigger-include or x-ms-documentdb-post-trigger-include. In the node.js SDK, you use the RequestOptions preTriggerInclude or preTriggerInclude property. For .NET, you specify it like this:

Document createdItem = await client.CreateDocumentAsync(collection.SelfLink, new Document { Id = "documentdb" },
new RequestOptions
{
    PreTriggerInclude = new List<string> { "CapitalizeName" },
});

See comments for discussion on the green squiggly.

like image 63
2 revs Avatar answered Feb 16 '23 03:02

2 revs