-
Notifications
You must be signed in to change notification settings - Fork 0
/
GetViewCounter.cs
67 lines (55 loc) · 2.25 KB
/
GetViewCounter.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
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 Microsoft.Azure.Cosmos.Table;
namespace PageViewCounter
{
public class ViewCount : TableEntity
{
public ViewCount(string URL)
{
this.PartitionKey = URL; //the partition key for load-balancing and identification
this.RowKey = "visits"; // hardcoded for identification
Count = 0; // the value we want to store
}
public int Count { get; set; }
public ViewCount()
{
Count = 0;
}
}
public static class PageViewCounter
{
const string tableName = "viewcountertable";
[FunctionName("GetPageViewCount")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
ILogger log)
{
var storageAccountConnectionString = Environment.GetEnvironmentVariable("StorageConnectionString");
var storageAccount = CloudStorageAccount.Parse($"{storageAccountConnectionString}");
var tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference(tableName);
await table.CreateIfNotExistsAsync(); // we can let our code create the table if needed
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
string pageViewURL = data?.URL;
if (pageViewURL == null)
{
return (ActionResult)new StatusCodeResult(503);
}
var retrievedResult = table.Execute(TableOperation.Retrieve<ViewCount>(pageViewURL, "visits"));
var pageView = (ViewCount)retrievedResult.Result;
pageView = pageView ?? new ViewCount(pageViewURL);
pageView.Count++;
table.Execute(TableOperation.InsertOrReplace(pageView));
return (ActionResult)new OkObjectResult(pageView.Count.ToString());
}
}
}