Added endpoint to update contact
This commit is contained in:
@@ -72,6 +72,73 @@ public class ContactsController : ControllerBase
|
|||||||
|
|
||||||
return Ok(response);
|
return Ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpPatch("update"), DisableRequestSizeLimit]
|
||||||
|
public IActionResult UpdateContact([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();
|
||||||
|
var users = userRepo.RetrieveAllUsers();
|
||||||
|
|
||||||
|
if (users.Count() == 0 || contacts.Count() == 0)
|
||||||
|
{
|
||||||
|
return BadRequest(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
var c = contacts.FirstOrDefault(c => c.Id!.Equals(contact.Id));
|
||||||
|
|
||||||
|
if (c == null ||
|
||||||
|
string.IsNullOrEmpty(contact.UserID))
|
||||||
|
{
|
||||||
|
// The Contact does not exists or no user id provided
|
||||||
|
return BadRequest(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!userRepo.Exists(contact.UserID!).Item1)
|
||||||
|
{
|
||||||
|
return BadRequest(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!c.UserID!.Equals(contact.UserID))
|
||||||
|
{
|
||||||
|
// The provided user id does is not the same that created the contact
|
||||||
|
return BadRequest(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(contact.Firstname))
|
||||||
|
{
|
||||||
|
c.Firstname = contact.Firstname;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(contact.Lastname))
|
||||||
|
{
|
||||||
|
c.Lastname = contact.Lastname;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(contact.PhoneNumber))
|
||||||
|
{
|
||||||
|
if (!contacts.Exists(cc => cc.PhoneNumber!.Equals(contact.PhoneNumber)))
|
||||||
|
{
|
||||||
|
c.PhoneNumber = contact.PhoneNumber;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
contactsRepo.Update(c);
|
||||||
|
response.Data.Add(c);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
this._logger.LogError($"An error occurred: {ex.Message}");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user