-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathNotesController.cs
98 lines (83 loc) · 3.09 KB
/
NotesController.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
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using net5_webapi.Engines;
using System.Security.Claims;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace net5_webapi.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class NotesController : ControllerBase
{
private readonly IDBEngine db;
public NotesController(IDBEngine DBEngine)
{
db = DBEngine;
}
/// <summary>
/// Returns all the Notes for this user.
/// </summary>
// GET: api/Notes
[HttpGet]
public async Task<ActionResult> Get()
{
string user = User.FindFirstValue(ClaimTypes.NameIdentifier);
return Ok(await db.JsonArray("SELECT * FROM Notes WHERE userId=@user", new { user }));
}
/// <summary>
/// Returns a specific Note (id) for this user.
/// </summary>
// GET api/Notes/{id}
[HttpGet("{id}")]
public async Task<ActionResult> Get(int id)
{
string user = User.FindFirstValue(ClaimTypes.NameIdentifier);
return Ok(await db.Json("SELECT * FROM Notes WHERE userId=@user AND ID=@id", new { user, id }));
}
public class NoteBody
{
[Required]
public string Text { get; set; }
}
/// <summary>
/// Creates a new Note for this user.
/// </summary>
// POST api/Notes
[HttpPost]
public async Task<ActionResult> Post([FromBody] NoteBody body)
{
string user = User.FindFirstValue(ClaimTypes.NameIdentifier);
return Ok(await db.Value<int>("INSERT INTO Notes (text, date, userId) VALUES (@text, GETDATE(), @user); SELECT SCOPE_IDENTITY()", new { body.Text, user }));
}
/// <summary>
/// Updates a specific Note (id) for this user.
/// </summary>
// PUT api/Notes/{id}
[HttpPut("{id}")]
public async Task<ActionResult> Put(int id, [FromBody] NoteBody body)
{
string user = User.FindFirstValue(ClaimTypes.NameIdentifier);
int found = await db.Value<int>("SELECT COUNT(*) FROM Notes WHERE ID=@id AND userID=@user;UPDATE Notes SET text=@text WHERE ID=@id AND userId=@user", new { body.Text, id, user });
if (found > 0)
return Ok("UPDATED: " + id);
else
return Unauthorized();
}
/// <summary>
/// Deletes a specific Note (id) for this user.
/// </summary>
// DELETE api/Notes/{id}
[HttpDelete("{id}")]
public async Task<ActionResult> Delete(int id)
{
string user = User.FindFirstValue(ClaimTypes.NameIdentifier);
int found = await db.Value<int>("SELECT COUNT(*) FROM Notes WHERE ID=@id AND userID=@user;DELETE Notes WHERE ID=@id AND userId=@user", new { id, user });
if (found > 0)
return Ok("DELETED: " + id);
else
return Unauthorized();
}
}
}