/
CustomersController.cs
77 lines (70 loc) · 2.63 KB
/
CustomersController.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
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using Pitstop.CustomerManagementAPI.DataAccess;
using Pitstop.CustomerManagementAPI.Model;
using Pitstop.Infrastructure.Messaging;
using Pitstop.CustomerManagementAPI.Events;
using Pitstop.CustomerManagementAPI.Commands;
using Pitstop.CustomerManagementAPI.Mappers;
using Serilog;
using System;
namespace Pitstop.Application.CustomerManagementAPI.Controllers
{
[Route("/api/[controller]")]
public class CustomersController : Controller
{
IMessagePublisher _messagePublisher;
CustomerManagementDBContext _dbContext;
public CustomersController(CustomerManagementDBContext dbContext, IMessagePublisher messagePublisher)
{
_dbContext = dbContext;
_messagePublisher = messagePublisher;
}
[HttpGet]
public async Task<IActionResult> GetAllAsync()
{
return Ok(await _dbContext.Customers.ToListAsync());
}
[HttpGet]
[Route("{customerId}", Name = "GetByCustomerId")]
public async Task<IActionResult> GetByCustomerId(string customerId)
{
var customer = await _dbContext.Customers.FirstOrDefaultAsync(c => c.CustomerId == customerId);
if (customer == null)
{
return NotFound();
}
return Ok(customer);
}
[HttpPost]
public async Task<IActionResult> RegisterAsync([FromBody] RegisterCustomer command)
{
try
{
if (ModelState.IsValid)
{
// insert customer
Customer customer = command.MapToCustomer();
_dbContext.Customers.Add(customer);
await _dbContext.SaveChangesAsync();
// send event
CustomerRegistered e = command.MapToCustomerRegistered();
await _messagePublisher.PublishMessageAsync(e.MessageType, e , "");
// return result
return CreatedAtRoute("GetByCustomerId", new { customerId = customer.CustomerId }, customer);
}
return BadRequest();
}
catch (DbUpdateException)
{
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists " +
"see your system administrator.");
return StatusCode(StatusCodes.Status500InternalServerError);
throw;
}
}
}
}