-
Notifications
You must be signed in to change notification settings - Fork 1
/
CreateRestaurantFunction.cs
56 lines (55 loc) · 2.27 KB
/
CreateRestaurantFunction.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
namespace MongoDB.Tutorials.AzureFunctions
{
public static class CreateRestaurantFunction
{
[FunctionName("CreateRestaurant")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("CreateRestaurant function processed a request.");
var itemId = ObjectId.Empty;
var jsonContent = string.Empty;
try
{
//retrieving the content from the request's body
jsonContent = await req.Content.ReadAsStringAsync().ConfigureAwait(false);
//assuming we have valid JSON content, convert to BSON
var doc = BsonSerializer.Deserialize<BsonDocument>(jsonContent);
var collection = RestaurantsCollection.Instance;
//store new document in MongoDB collection
await collection.InsertOneAsync(doc).ConfigureAwait(false);
//retrieve the _id property created document
itemId = (ObjectId)doc["_id"];
}
catch (System.FormatException fex)
{
//thrown if there's an error in the parsed JSON
log.Error($"A format exception occurred, check the JSON document is valid: {jsonContent}", fex);
}
catch (System.TimeoutException tex)
{
log.Error("A timeout error occurred", tex);
}
catch (MongoException mdbex)
{
log.Error("A MongoDB error occurred", mdbex);
}
catch (System.Exception ex)
{
log.Error("An error occurred", ex);
}
return itemId == ObjectId.Empty
? req.CreateResponse(HttpStatusCode.BadRequest, "An error occurred, please check the function log")
: req.CreateResponse(HttpStatusCode.OK, $"The created item's _id is {itemId}");
}
}
}