-
Notifications
You must be signed in to change notification settings - Fork 1
/
CreateRating.cs
61 lines (49 loc) · 2.46 KB
/
CreateRating.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
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using BFYOC.Models;
namespace BFYOC
{
public static class CreateRating
{
private static readonly ProductService productService = new ProductService();
private static readonly UserService userService = new UserService();
private static readonly RatingService ratingService = new RatingService();
[FunctionName("CreateRating")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
[CosmosDB("BFYOC", "rating", ConnectionStringSetting="CosmosConnection")]IAsyncCollector<Models.CreateRatingResponse> document,
ILogger log)
{
log.LogInformation("Create Rating function called");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var createRatingRequest = JsonConvert.DeserializeObject<CreateRatingRequest>(requestBody);
// validate the product id is a guid
if (!Guid.TryParse(createRatingRequest.ProductId, out Guid productId))
return new BadRequestObjectResult("ProductId is not a guid");
// validate the product exists
var product = await productService.GetProductAsync(productId);
if (product == null)
return new NotFoundObjectResult($"product {productId} was not found");
// validate user id is a guid
if (!Guid.TryParse(createRatingRequest.UserId, out Guid userId))
return new BadRequestObjectResult("UserId is not a guid");
// validate the user exists
var user = await userService.GetUserAsync(userId);
if(user == null)
return new NotFoundObjectResult($"user {userId} was not found");
// validate rating is between 0 and 5
if(createRatingRequest.Rating < 0 || createRatingRequest.Rating > 5)
return new BadRequestObjectResult("Rating must be a value between 0 and 5");
var response = ratingService.Create(createRatingRequest);
await document.AddAsync(response);
return new CreatedResult("ratings", response);
}
}
}