I am trying to insert data from azure javascript function app to cosmos DB.
This is the function.json File
{
"bindings": [
{
"type": "cosmosDBTrigger",
"name": "documents",
"direction": "in",
"leaseCollectionName": "leases",
"connectionStringSetting": "CosmosDBConnection",
"databaseName": "roi",
"collectionName": "reports",
"createLeaseCollectionIfNotExists": "true"
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
index.js have a code like this.
module.exports = async function (context, documents) {
if (!!documents && documents.length > 0) {
context.log('Document Id: ', documents[0].id);
}
}
Below images will have the error in the application.
Is there any function or query to insert the data ? the request data which is coming from api will look like this.(its coming in rawBody property of request)
When i am fetching the data its workign fine.
{
"name": "inputDocumentIn",
"type": "cosmosDB",
"databaseName": "roi",
"collectionName": "reports",
"sqlQuery": "SELECT * from reports r",
"connectionStringSetting": "CosmosDBConnection",
"direction": "in"
}
local.setting.json file
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "",
"FUNCTIONS_WORKER_RUNTIME": "node",
"CosmosDBConnection": "AccountEndpoint=.....;"
},
"Host": {
"LocalHttpPort": 7071,
"CORS": "*"
}
}
With this azure value in local.setting.ts file , i m getting following error.
Please check if the Connection String is pointing to the correct account and check if it was caused by the firewall and networks. Go to your cosmos db account on azure portal and click "Firewall and virtual networks". You can select "All networks" or "Selected networks" with your current IP filled in it.
This sounds like some some dependency conflict. Could you do a dotnet clean on the project folder and then verify that all projects (in case you have project dependencies) have the latest version of the Microsoft.Azure.WebJobs.Extensions.CosmosDB package (currently 3.0.5)?
The solution of the above problem is :
I have changed function.json file with this code.
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"methods": [ "post" ],
"name": "req"
},
{
"type": "http",
"direction": "out",
"name": "res"
},
{
"type": "cosmosDB",
"name": "outputDocument",
"databaseName": "roi",
"collectionName": "reports",
"createIfNotExists": true,
"connectionStringSetting": "CosmosDBConnection",
"direction": "out",
"partitionKey": "/id"
}
],
"disabled": false
}
and the request coming from front end will be manipulate like this.
module.exports = function (context, req) {
if (req.body) {
context.bindings.outputDocument = req.body;
var responseBody = {};
responseBody.message = "Wow! data with id '" + req.body.id + "' was created!";
context.res = {
status: 201,
body:responseBody
};
}
else {
context.res = {
status: 400,
body: { "message" : "Please pass a valid object in the request body"}
};
}
context.done();
}
Related
i am using azure functions written in nodejs.
I have this azure function
module.exports = async function (context, req) {
const title = req.body.title;
console.log('title', title);
if (title) {
req.body.completed = false;
context.bindings.outputDocument = req.body;
context.res = {
body: { success: true, message: `Todo added successfully` }
};
} else {
context.res = {
status: 400,
body: { success: false, message: `Please add title field` }
};
}
};
and the binding
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
},
{
"type": "cosmosDB",
"name": "outputDocument",
"databaseName": "xxx",
"collectionName": "items",
"createIfNotExists": false,
"connectionStringSetting": "xxx",
"partitionKey": "/all",
"direction": "out"
}
],
"disabled": false
}
locally when i run
func host start
i don't see my console log statement.
How can i see on localhost ?
And where i need to go in my azure portal to see the logs there after deployment.
I tried to go in Function App - open my function and there the azure function but i can't see any logs there...
How can i see on localhost ?
And where i need to go in my azure portal to see the logs there after
deployment.
I tried to go in Function App - open my function and there the azure
function but i can't see any logs there...
Of course, you can get the log files on local. I assume you are based on windows, then just edit the host.json like this:
{
"version": "2.0",
"logging": {
"fileLoggingMode": "always",
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[1.*, 2.0.0)"
}
}
And go to
C:\Users\yourusernameonlocal\AppData\Local\Temp\LogFiles\Application\Functions\Function\yourfunctionname
After that you will see the log files.:)
This should probably resolve your issue.
Azure Functions JavaScript developer guide:
Don't use console.log to write trace outputs. Because output from console.log is captured at the function app level, it's not tied to a specific function invocation and isn't displayed in a specific function's logs.
I have azure functions written in nodejs. I can't find a way how to get data for example from my created azure cosmos db. I know that there is azure cosmos SDK, but i don't want to use that way.I want to learn to do it through the azure functions because it is possible with them also.
i try do to this:
function.json
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
},
{
"type": "cosmosDB",
"name": "inputDocument",
"databaseName": "dbtodos",
"collectionName": "items",
"connectionStringSetting": "todos_DOCUMENTDB",
"partitionKey": "/all",
"direction": "in"
}
],
"disabled": false
}
index
module.exports = async function (context, req) {
context.res = {
// status: 200, /* Defaults to 200 */
body: context.bindings.inputDocument
};
};
after my deploy when i visit the automatically generated url - i can't even open the link.There is not requests coming back.
If i do some basic example where i don't try to pull data from the db then my url is working after deploy.
How can i get the data ?
My data in the local.settings.json was wrong. I had azure storage for other table not for the one that i wanted to query... The code works perfectly fine
I have simple azure function which is triggered by http
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
context.res = {
// status: 200, /* Defaults to 200 */
body: "Success"
};
}
function.json
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
At this point I can trigger the function and see the response.
Then I try to add a service bus binding to function.json
{
"bindings": [
...
{
"type": "serviceBus",
"direction": "out",
"name": "outputSbTopic",
"topicName": "topicName",
"connection": "ServiceBusConnection"
}
]
}
When I add the binding the function returns 404 and there is nothing in log. I've even not started to use the binding.
What can be wrong? I'm struggling with the issue more than 2 hours and have no more ideas.
host.json (just in case)
{
"version": "2.0",
"extensions": {
"serviceBus": {
"prefetchCount": 100,
"messageHandlerOptions": {
"autoComplete": true,
"maxConcurrentCalls": 32,
"maxAutoRenewDuration": "00:05:00"
}
}
}
}
Runtime version ~2
Node.js Version Node.js 12 LTS
App is run in read only mode from a package file.
AppType functionAppLinux
UPDATE
I created the function with VS Code Azure Function Extension and deployed with DevOps. Later I created function in azure portal manually. Compared with App Service Editor files of both functions and found out that my first function doesn't have extensionBundle in host.json. That was the reason.
Use your host.json also get the same problem:
The problem seems comes from the host.json in your function app.
On my side those files is:
index.js
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
var message = "This is a test to output to service bus.";
context.bindings.testbowman = message;
context.done();
context.res = {
status: 200,
body: "This is a test to output to service bus topic."
};
};
function.json
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
},
{
"name": "testbowman",
"type": "serviceBus",
"topicName": "testbowman",
"connection": "str",
"direction": "out"
}
]
}
host.json
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[1.*, 2.0.0)"
}
}
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "node",
"str":"Endpoint=sb://testbowman.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xxxxxx="
}
}
And it worked:
I am new to cosmos db as well as azure functions and I'm getting nowhere fast. I've been able to find every tutorial under the sun to create and read documents but not update and delete. No one seems to have a full CRUD tutorial using azure functions.
Can someone show me a typical .csx file in azure functions that takes a document in, updates it, and returns an OK response?
I've tried this already
#load "..\Shared\Classes.csx"
using System.Net;
public static HttpResponseMessage Run(HttpRequestMessage req,
IEnumerable<Business> businessToBeUpdated, out dynamic updatedBusiness,
TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
//compiler requires this assignment
updatedBusiness = null;
// Get request body
Business data = req.Content.ReadAsAsync<Business>().Result;
businessToBeUpdated = businessToBeUpdated.FirstOrDefault<Business>();
log.Info(businessToBeUpdated.Count().ToString());
if(businessToBeUpdated != null && data != null)
{
//update it
businessToBeUpdated = data;
//updatedBusiness.id = data.id;
log.Info(businessToBeUpdated.website);
}
else{
return req.CreateResponse(HttpStatusCode.BadRequest);
}
return req.CreateResponse(HttpStatusCode.OK);
}
Here is the binding associated with it.
{
"bindings": [
{
"authLevel": "anonymous",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"route": "updatebiz/{id}"
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "documentDB",
"name": "businessToBeUpdated",
"databaseName": "dbname",
"collectionName": "Businesses",
"sqlQuery": "Select * FROM c where c.id = {id}",
"connection": "connection",
"direction": "in"
},
{
"type": "documentDB",
"name": "updatedBusiness",
"databaseName": "dbname",
"collectionName": "Businesses",
"createIfNotExists": false,
"connection": "connection",
"direction": "out"
}
],
"disabled": false
}
The simplest example of a function which updates a document looks exactly the same as the function which creates a document: function will do one or the other based on whether the document with specified id already exists.
You don't mention which exact problem you face. Your code doesn't even compile, having enumerable and single objects assigned to each other. On top of that, you never assign updatedBusiness to anything other than null.
I came with a working example which does what I assume you were trying to accomplish.
csx script:
using System.Net;
public class Business
{
public string id { get; set;}
public string name { get; set;}
}
public static HttpResponseMessage Run(HttpRequestMessage req,
Business businessToBeUpdated, out Business updatedBusiness, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
var data = req.Content.ReadAsAsync<Business>().Result;
if(businessToBeUpdated == null || data == null)
{
updatedBusiness = businessToBeUpdated;
return req.CreateResponse(HttpStatusCode.BadRequest);
}
updatedBusiness = data;
// or merge data and businessToBeUpdated in some desired way
return req.CreateResponse(HttpStatusCode.OK);
}
function.json:
{
"bindings": [
{
"authLevel": "anonymous",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"route": "updatebiz/{id}"
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "documentDB",
"name": "businessToBeUpdated",
"databaseName": "dbname",
"collectionName": "Businesses",
"id": "{id}",
"connection": "connection",
"direction": "in"
},
{
"type": "documentDB",
"name": "updatedBusiness",
"databaseName": "dbname",
"collectionName": "Businesses",
"id": "{id}",
"connection": "connection",
"direction": "out"
}
],
"disabled": false
}
So what I read from this page, is that I should be able to have:
trigger HTTP
input Http request
input DocumentDb
output DocumentDb
Numbers 1, 2 and 4 are working. But how to get a document from DocumentDB with the ID from the path?
Can I use the {path} from the proxy-route in my DocumentDb Input?
I have a proxy defined like so.
{
"$schema": "http://json.schemastore.org/proxies",
"proxies": {
"index": {
"matchCondition": {
"route": "{*path}",
"methods": [
"GET"
]
},
"backendUri": "https://%WEBSITE_SITE_NAME%.azurewebsites.net/api/Index"
},
"api": {
"matchCondition": {
"route": "api/{*path}"
},
"backendUri": "https://%WEBSITE_SITE_NAME%.azurewebsites.net/api/{path}"
},
"index existing subscription": {
"matchCondition": {
"route": "/subscription/{*path}",
"methods": [
"GET"
]
},
"backendUri": "https://%WEBSITE_SITE_NAME%.azurewebsites.net/api/IndexSubscription/{path}"
}
}
}
Here is an example of a Function with Document DB input binding.
function.json
{
"bindings": [
{
"authLevel": "function",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"route": "MyDocFunc/{docid}"
},
{
"type": "documentDB",
"name": "inputDocument",
"databaseName": "MyDocDB",
"collectionName": "MyCollection",
"id": "{docid}",
"connection": "mydocdb_DOCUMENTDB",
"direction": "in"
},
{
"name": "$return",
"type": "http",
"direction": "out"
}
],
"disabled": false
}
csx
public static async Task<HttpResponseMessage> Run(
HttpRequestMessage req, string docid, string inputDocument)
{
return req.CreateResponse(HttpStatusCode.OK, inputDocument);
}
The usage of proxy doesn't affect this much... You can pass your proxy parameter to function parameter.