public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("upsert_daily_survey function processed a request."); DailySurveyData dailySurveyData = await upsert_daily_survey.PopulateDailySurveyDataFromHttpRequest(req); dailySurveyData.EntryDate = DateTime.Today.Date.ToString(); string responseMessage = ""; if (string.IsNullOrEmpty(dailySurveyData.PatientId)) { responseMessage = "{\"result\":\"PatientId parameter is missing in your request\"}"; return(new OkObjectResult(responseMessage)); } else { // Input user data to Cosmos DB await upsert_daily_survey.WriteToCosmosDB(dailySurveyData); responseMessage = "{\"result\":\"wrote " + 1 + " record(s) to db\"}"; return(new OkObjectResult(responseMessage)); } }
// Utility method to extract daily survey data from HTTP request query params or request body private static async Task <DailySurveyData> PopulateDailySurveyDataFromHttpRequest(HttpRequest request) { // Reading request body string requestBody = await new StreamReader(request.Body).ReadToEndAsync(); DailySurveyData dailySurveyData = JsonConvert.DeserializeObject <DailySurveyData>(requestBody); return(dailySurveyData); }
// Utility method to write user data to Cosmos Database private static async Task WriteToCosmosDB(DailySurveyData dailySurveyData) { // Create a new instance of the Cosmos Client upsert_daily_survey.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey, new CosmosClientOptions() { ApplicationName = "CosmosDBDotnetQuickstart" }); await upsert_daily_survey.CreateDatabaseAsync(); await upsert_daily_survey.CreateContainerAsync(); await upsert_daily_survey.ScaleContainerAsync(); await upsert_daily_survey.AddItemsToContainerAsync(dailySurveyData); }
/// Add initial assessment items to the container private static async Task AddItemsToContainerAsync(DailySurveyData dailySurveyData) { try { // Create an item in the container representing the user data. Note we provide the value of the partition key for upsert_daily_survey item, which is "Andersen" ItemResponse <DailySurveyData> dailySurveyDataResponse = await upsert_daily_survey.container.CreateItemAsync <DailySurveyData>(dailySurveyData, new PartitionKey(dailySurveyData.EntryDate)); // Note that after creating the item, we can access the body of the item with the Resource property off the ItemResponse. We can also access the RequestCharge property to see the amount of RUs consumed on this request. Console.WriteLine("Created item in database with id: {0} Operation consumed {1} RUs.\n", dailySurveyDataResponse.Resource.Id, dailySurveyDataResponse.RequestCharge); } catch (CosmosException ex) when(ex.StatusCode == System.Net.HttpStatusCode.Conflict) { Console.WriteLine("Item in database with id: {0} already exists\n", dailySurveyData.Id); } }