-
Notifications
You must be signed in to change notification settings - Fork 1
/
RestaurantFunction.cs
114 lines (102 loc) · 4.99 KB
/
RestaurantFunction.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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 RestaurantFunction
{
[FunctionName("Restaurant")]
public static Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "patch", "delete", Route = "Restaurant/id/{restaurantId}")]HttpRequestMessage req, string restaurantId, TraceWriter log)
{
log.Info("Restaurant function processed a request.");
try
{
var collection = RestaurantsCollection.Instance;
switch (req.Method.Method)
{
case "GET":
return RunGet(req, restaurantId, log, collection);
case "PATCH":
return RunPatch(req, restaurantId, log, collection);
case "DELETE":
return RunDelete(req, restaurantId, log, collection);
default:
return Task.FromResult(req.CreateResponse(HttpStatusCode.MethodNotAllowed));
}
}
catch (System.Exception ex)
{
log.Error("An error occurred", ex);
return Task.FromResult(req.CreateResponse(HttpStatusCode.InternalServerError));
}
}
private static async Task<HttpResponseMessage> RunGet(HttpRequestMessage req, string restaurantId, TraceWriter log, IMongoCollection<BsonDocument> collection)
{
var filter = Builders<BsonDocument>.Filter.Eq("restaurant_id", restaurantId);
var results = await collection.Find(filter).ToListAsync().ConfigureAwait(false);
if (results.Count > 0)
{
return req.CreateResponse(HttpStatusCode.OK, results[0].ToString());
}
return req.CreateResponse(HttpStatusCode.NotFound, $"A restaurant with id {restaurantId} could not be found");
}
private static async Task<HttpResponseMessage> RunDelete(HttpRequestMessage req, string restaurantId, TraceWriter log, IMongoCollection<BsonDocument> collection)
{
var filter = Builders<BsonDocument>.Filter.Eq("restaurant_id", restaurantId);
var result = await collection.FindOneAndDeleteAsync(filter).ConfigureAwait(false);
if (result != null)
{
return req.CreateResponse(HttpStatusCode.OK);
}
return req.CreateResponse(HttpStatusCode.NotFound, $"A restaurant with id {restaurantId} could not be deleted");
}
private static async Task<HttpResponseMessage> RunPatch(HttpRequestMessage req, string restaurantId, TraceWriter log, IMongoCollection<BsonDocument> collection)
{
var filter = Builders<BsonDocument>.Filter.Eq("restaurant_id", restaurantId);
string jsonContent = await req.Content.ReadAsStringAsync();
BsonDocument changesDocument;
try
{
changesDocument = BsonSerializer.Deserialize<BsonDocument>(jsonContent);
}
catch (System.FormatException)
{
var msg = $"The JSON content is invalid: {jsonContent}";
log.Info(msg);
return req.CreateResponse(HttpStatusCode.BadRequest, msg);
}
//UpdateDefinition requires dot notation (such as "address.zipcode" instead of "address": {"zipcode:<value>} to preserve other attributes in subdocument)
UpdateDefinition<BsonDocument> update = null;
foreach (var change in changesDocument)
{
if (update == null)
{
update = Builders<BsonDocument>.Update.Set(change.Name, change.Value);
}
else
{
update = update.Set(change.Name, change.Value);
}
}
//you can also use the simpler form below if you're OK with bypassing the UpdateDefinitionBuilder (and trust the JSON string to be fully correct)
//update = new BsonDocument("$set", changesDocument);
//The following lines could be uncommented out for debugging purposes
//var registry = collection.Settings.SerializerRegistry;
//var serializer = collection.DocumentSerializer;
//var rendered = update.Render(serializer, registry).ToJson();
var updateResult = await collection.UpdateOneAsync(filter, update).ConfigureAwait(false);
if (updateResult.ModifiedCount == 1)
{
return req.CreateResponse(HttpStatusCode.OK);
}
return req.CreateResponse(HttpStatusCode.NotFound, $"A restaurant with id {restaurantId} could not be updated");
}
}
}