-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpenseController.cs
More file actions
184 lines (152 loc) · 5.99 KB
/
Copy pathExpenseController.cs
File metadata and controls
184 lines (152 loc) · 5.99 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
//1 //這個 API Controller 用來處理 Expense 相關的 HTTP Reques
//這個 API Controller 會使用 ExpenseContext 來存取資料庫 _context = context;
// api path 是 /api/expense
// GET: api/Expense
using ExpenseAPI.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace ExpenseAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class ExpenseController : ControllerBase
{
private const string LunchDescription = "午餐";
private const string LunchAmountLimitExceededMessage = "午餐費用不能超過400元";
private readonly ExpenseContext _context;
private readonly ILogger<ExpenseController> _logger;
public ExpenseController(ExpenseContext context, ILogger<ExpenseController> logger)
{
_context = context;
_logger = logger;
}
// GET: /Expense
[HttpGet]
public async Task<ActionResult<IEnumerable<Expense>>> GetExpenses()
{
_logger.LogInformation("Retrieving all expenses");
return await _context.Expenses.ToListAsync();
}
// GET: /Expense/{id}
[HttpGet("{id}")]
public async Task<ActionResult<Expense>> GetExpense(int id)
{
_logger.LogInformation("Retrieving expense with id: {ExpenseId}", id);
var expense = await _context.Expenses.FindAsync(id);
if (expense == null)
{
_logger.LogWarning("Expense with id: {ExpenseId} not found", id);
return NotFound();
}
return expense;
}
// POST: /Expense
//提供了如何使用 curl 呼叫的範例
//curl -X POST -H "Content-Type: application/json" -d "{\"date\":\"2021-01-01\",\"description\":\"午餐\",\"amount\":500}" https://localhost:7039/Expense
//並提到如果描述是午餐,且Amount範圍超過400,說明午餐不能夠報銷。
[HttpPost]
public async Task<ActionResult<Expense>> PostExpense(Expense expense)
{
var validationResult = ValidateExpense(expense);
if (validationResult is not null)
{
return validationResult;
}
_context.Expenses.Add(expense);
await _context.SaveChangesAsync();
_logger.LogInformation("Created expense with id: {ExpenseId}", expense.Id);
return CreatedAtAction(nameof(GetExpense), new { id = expense.Id }, expense);
}
// PUT: /Expense/{id}
[HttpPut("{id}")]
public async Task<IActionResult> PutExpense(int id, ExpenseUpdateRequest expense)
{
if (expense.Id.HasValue && id != expense.Id.Value)
{
_logger.LogWarning("Mismatched expense id for update. Route id: {RouteId}, Expense id: {ExpenseId}", id, expense.Id);
return BadRequest();
}
var existingExpense = await _context.Expenses.FindAsync(id);
if (existingExpense == null)
{
_logger.LogWarning("Expense with id: {ExpenseId} not found during update", id);
return NotFound();
}
if (expense.Date.HasValue)
{
existingExpense.Date = expense.Date.Value;
}
if (expense.Description is not null)
{
existingExpense.Description = expense.Description;
}
if (expense.Amount.HasValue)
{
existingExpense.Amount = expense.Amount.Value;
}
if (expense.Category is not null)
{
existingExpense.Category = expense.Category;
}
if (expense.Title is not null)
{
existingExpense.Title = expense.Title;
}
var validationResult = ValidateExpense(existingExpense);
if (validationResult is not null)
{
return validationResult;
}
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!await _context.Expenses.AnyAsync(e => e.Id == id))
{
_logger.LogWarning("Expense with id: {ExpenseId} no longer exists during update", id);
return NotFound();
}
throw;
}
_logger.LogInformation("Updated expense with id: {ExpenseId}", id);
return NoContent();
}
// DELETE: /Expense/{id}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteExpense(int id)
{
var expense = await _context.Expenses.FindAsync(id);
if (expense == null)
{
_logger.LogWarning("Expense with id: {ExpenseId} not found for deletion", id);
return NotFound();
}
_context.Expenses.Remove(expense);
await _context.SaveChangesAsync();
_logger.LogInformation("Deleted expense with id: {ExpenseId}", id);
return NoContent();
}
private BadRequestObjectResult? ValidateExpense(Expense expense)
{
if (string.IsNullOrWhiteSpace(expense.Description))
{
_logger.LogWarning("Description is required");
return BadRequest("Description is required");
}
if (expense.Description == LunchDescription && expense.Amount > 400)
{
_logger.LogWarning("Lunch expense with amount over 400 is not allowed");
return BadRequest(LunchAmountLimitExceededMessage);
}
if (expense.Amount < 0)
{
_logger.LogWarning("數量不能為負的");
return BadRequest("數量不能為負的");
}
return null;
}
}
}