/
Function.cs
executable file
·88 lines (77 loc) · 2.87 KB
/
Function.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
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using Amazon.Lambda.RuntimeSupport;
using Amazon.Lambda.Serialization.SystemTextJson;
using Amazon.XRay.Recorder.Handlers.AwsSdk;
using Shared;
using Shared.DataAccess;
using Shared.Models;
public class Function
{
private static ProductsDAO dataAccess;
static Function()
{
AWSSDKHandler.RegisterXRayForAllServices();
dataAccess = new DynamoDbProducts();
}
/// <summary>
/// The main entry point for the custom runtime.
/// </summary>
/// <param name="args"></param>
private static async Task Main()
{
Func<APIGatewayHttpApiV2ProxyRequest, ILambdaContext, Task<APIGatewayHttpApiV2ProxyResponse>> handler = FunctionHandler;
await LambdaBootstrapBuilder.Create(handler, new SourceGeneratorLambdaJsonSerializer<CustomJsonSerializerContext>(options => {
options.PropertyNameCaseInsensitive = true;
}))
.Build()
.RunAsync();
}
public static async Task<APIGatewayHttpApiV2ProxyResponse> FunctionHandler(APIGatewayHttpApiV2ProxyRequest apigProxyEvent, ILambdaContext context)
{
if (!apigProxyEvent.RequestContext.Http.Method.Equals(HttpMethod.Put.Method))
{
return new APIGatewayHttpApiV2ProxyResponse
{
Body = "Only PUT allowed",
StatusCode = (int)HttpStatusCode.MethodNotAllowed,
};
}
try
{
context.Logger.LogLine(JsonSerializer.Serialize(apigProxyEvent, CustomJsonSerializerContext.Default.APIGatewayHttpApiV2ProxyRequest));
var id = apigProxyEvent.PathParameters["id"];
var product = JsonSerializer.Deserialize(apigProxyEvent.Body, CustomJsonSerializerContext.Default.Product);
if (product == null || id != product.Id)
{
return new APIGatewayHttpApiV2ProxyResponse
{
Body = "Product ID in the body does not match path parameter",
StatusCode = (int)HttpStatusCode.BadRequest,
};
}
await dataAccess.PutProduct(product);
return new APIGatewayHttpApiV2ProxyResponse
{
StatusCode = (int)HttpStatusCode.Created,
Body = $"Created product with id {id}"
};
}
catch (Exception e)
{
context.Logger.LogError($"Error creating product {e.Message} {e.StackTrace}");
return new APIGatewayHttpApiV2ProxyResponse
{
Body = "Not Found",
StatusCode = (int)HttpStatusCode.InternalServerError,
};
}
}
}