Creating Trip Data With Azure Functions and Cosmos DB

In my previous post I reviewed the bindings that are setup for an Azure function that handles POST requests for the trip logger service. For this post I will be reviewing the simple code that translates the posted data to a trip entry to be saved in Cosmos DB. The initial setup only contains one Azure Function that supports POSTing data to create trips in Cosmos DB.

Deserializing the Data

Following the template Azure Function you can get the string request body from the passed in HttpRequest object (line 1).

var requestBody = new StreamReader(req.Body).ReadToEnd();
var postRequest = JsonConvert.DeserializeObject<TripPost>(requestBody);

if (string.IsNullOrWhiteSpace(postRequest.TripFrom)) return new BadRequestObjectResult($"{nameof(postRequest.TripFrom)} missing");
if (string.IsNullOrWhiteSpace(postRequest.TripTo)) return new BadRequestObjectResult($"{nameof(postRequest.TripTo)} missing");
if (string.IsNullOrWhiteSpace(postRequest.Description)) return new BadRequestObjectResult($"{nameof(postRequest.Description)} missing");
if (postRequest.Distance == null) return new BadRequestObjectResult($"{nameof(postRequest.Distance)} missing");

But instead of deserializing the JSON to a dynamic object I have created a POST model and I deserialize the JSON to the TripPost model (line 2).

Once I have the deserialized TripPost I perform some simple validation (lines 4-7). I will have to explore ways to perform more advanced validation later.

Creating the Trip Entry

Once I have the deserialized TripPost data and the data is validated the next step is to translate the post data to a new TripEntry object. I first generate a new Guid (line 2) to assign to the Id of the TripEntry. Then I create a new TripEntry object and copy over the post data using the object initializer syntax (lines 5-13).

// create id
var tripId = Guid.NewGuid();

// create trip cosmos db model
tripEntry = new TripEntry
{
	Id = tripId,
	Date = postRequest.Date,
	Distance = postRequest.Distance,
	TripFrom = postRequest.TripFrom,
	TripTo = postRequest.TripTo,
	Description = postRequest.Description,
};

// return results
return new OkObjectResult($"{tripId}");

The important thing to note is that the out tripEntry parameter is assigned the new TripEntry object (line 5). The CosmosDB attribute handles saving the tripEntry object to Cosmos DB for you automatically. The last step on the happy path is to return the OkObjectResult with the generated tripId as the content of the response.

Leave a comment