-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFeedbackController.cs
More file actions
105 lines (92 loc) · 2.94 KB
/
Copy pathFeedbackController.cs
File metadata and controls
105 lines (92 loc) · 2.94 KB
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
99
100
101
102
103
104
105
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using TransitAnalyticsAPI.Models.Dto;
using TransitAnalyticsAPI.Models.Entities;
using TransitAnalyticsAPI.Persistence;
namespace TransitAnalyticsAPI.Controllers;
[ApiController]
[Route("feedback")]
public class FeedbackController : ControllerBase
{
private readonly AppDbContext _dbContext;
private readonly TimeProvider _timeProvider;
public FeedbackController(AppDbContext dbContext, TimeProvider timeProvider)
{
_dbContext = dbContext;
_timeProvider = timeProvider;
}
[HttpPost]
[EnableRateLimiting("feedback-submissions")]
public async Task<IActionResult> Create(
[FromBody] FeedbackSubmissionRequestDto request,
CancellationToken cancellationToken)
{
string name = request.Name.Trim();
string email = request.Email.Trim();
string message = request.Message.Trim();
string ip = ResolveIp();
if (string.IsNullOrWhiteSpace(name))
{
return BadRequest(new
{
error = "invalid_name",
message = "A name is required."
});
}
if (string.IsNullOrWhiteSpace(email))
{
return BadRequest(new
{
error = "invalid_email",
message = "An email is required."
});
}
if (string.IsNullOrWhiteSpace(message))
{
return BadRequest(new
{
error = "invalid_message",
message = "A message is required."
});
}
var submission = new FeedbackSubmission
{
CreatedAtUtc = _timeProvider.GetUtcNow().UtcDateTime,
Name = name,
Email = email,
Message = message,
Ip = ip
};
_dbContext.FeedbackSubmissions.Add(submission);
await _dbContext.SaveChangesAsync(cancellationToken);
return CreatedAtAction(nameof(GetById), new { id = submission.Id }, new
{
id = submission.Id,
createdAtUtc = submission.CreatedAtUtc
});
}
[HttpGet("{id:long}")]
[ApiExplorerSettings(IgnoreApi = true)]
public async Task<IActionResult> GetById(long id, CancellationToken cancellationToken)
{
var submission = await _dbContext.FeedbackSubmissions
.AsNoTracking()
.Where(item => item.Id == id)
.Select(item => new
{
item.Id,
item.CreatedAtUtc,
item.Name,
item.Email,
item.Message,
item.Ip
})
.SingleOrDefaultAsync(cancellationToken);
return submission is null ? NotFound() : Ok(submission);
}
private string ResolveIp()
{
return HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
}
}