-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpTriggerTodoAPIMem.cs
83 lines (71 loc) · 3.1 KB
/
HttpTriggerTodoAPIMem.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
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
namespace AzureFunctionsTodo
{
public static class TodoApiInMemory
{
static List<Todo> items = new List<Todo>();
[FunctionName("InMemory_CreateTodo")]
public static async Task<IActionResult>CreateTodo([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "todo")]HttpRequest req, TraceWriter log)
{
log.Info("Creating a new todo list item");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var input = JsonConvert.DeserializeObject<TodoCreateModel>(requestBody);
var todo = new Todo() { TaskDescription = input.TaskDescription };
items.Add(todo);
return new OkObjectResult(todo);
}
[FunctionName("InMemory_GetTodos")]
public static IActionResult GetTodos([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "todo")]HttpRequest req, TraceWriter log)
{
log.Info("Getting todo list items");
return new OkObjectResult(items);
}
[FunctionName("InMemory_GetTodoById")]
public static IActionResult GetTodoById([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "todo/{id}")]HttpRequest req, TraceWriter log, string id)
{
var todo = items.FirstOrDefault(t => t.Id == id);
if (todo == null)
{
return new NotFoundResult();
}
return new OkObjectResult(todo);
}
[FunctionName("InMemory_UpdateTodo")]
public static async Task<IActionResult> UpdateTodo([HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "todo/{id}")]HttpRequest req, TraceWriter log, string id)
{
var todo = items.FirstOrDefault(t => t.Id == id);
if (todo == null)
{
return new NotFoundResult();
}
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var updated = JsonConvert.DeserializeObject<TodoUpdateModel>(requestBody);
todo.IsCompleted = updated.IsCompleted;
if (!string.IsNullOrEmpty(updated.TaskDescription))
{
todo.TaskDescription = updated.TaskDescription;
}
return new OkObjectResult(todo);
}
[FunctionName("InMemory_DeleteTodo")]
public static IActionResult DeleteTodo([HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "todo/{id}")]HttpRequest req, TraceWriter log, string id)
{
var todo = items.FirstOrDefault(t => t.Id == id);
if (todo == null)
{
return new NotFoundResult();
}
items.Remove(todo);
return new OkResult();
}
}
}