87 lines
2.1 KiB
C#
87 lines
2.1 KiB
C#
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Newtonsoft.Json;
|
|
|
|
using TextSender_API.Models;
|
|
using TextSender_API.Repositories;
|
|
|
|
namespace TextSender_API.Controllers;
|
|
|
|
[Authorize]
|
|
[ApiController]
|
|
[Route("api/v1/contact")]
|
|
public class ContactsController : ControllerBase
|
|
{
|
|
#region Fields
|
|
private IConfiguration _config;
|
|
private readonly ILogger<ContactsController> _logger;
|
|
#endregion
|
|
|
|
|
|
#region Constructors
|
|
|
|
public ContactsController(ILogger<ContactsController> logger, IConfiguration config)
|
|
{
|
|
this._logger = logger;
|
|
this._config = config;
|
|
}
|
|
#endregion
|
|
|
|
#region Methods
|
|
[HttpPost("new"), DisableRequestSizeLimit]
|
|
public IActionResult CreateContact([FromBody] Contact contact)
|
|
{
|
|
var response = new CreateContactResponse();
|
|
var connString = this._config.GetConnectionString("MongoDBURI");
|
|
var userRepo = new UsersRepository(connString!);
|
|
var contactsRepo = new ContactsRepository(connString!);
|
|
|
|
try
|
|
{
|
|
var contacts = contactsRepo.RetrieveAll();
|
|
|
|
if (contacts.Exists(c => c.PhoneNumber!.Equals(contact.PhoneNumber)) ||
|
|
string.IsNullOrEmpty(contact.UserID))
|
|
{
|
|
// The Contact already exists
|
|
return BadRequest(response);
|
|
}
|
|
|
|
var user = new User { Id = contact.UserID };
|
|
|
|
if (!userRepo.Exists(user).Item1)
|
|
{
|
|
return BadRequest(response);
|
|
}
|
|
|
|
contactsRepo.Create(contact);
|
|
response.Data.Add(contact);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this._logger.LogError($"An error occurred: {ex.Message}");
|
|
}
|
|
|
|
return Ok(response);
|
|
}
|
|
#endregion
|
|
|
|
|
|
#region Responses
|
|
public class CreateContactResponse
|
|
{
|
|
#region Properties
|
|
[JsonProperty("data")]
|
|
public List<Contact> Data { get; set; }
|
|
#endregion
|
|
|
|
#region Constructors
|
|
public CreateContactResponse()
|
|
{
|
|
this.Data = new List<Contact>();
|
|
}
|
|
#endregion
|
|
}
|
|
#endregion
|
|
}
|