Hi I am creating a website for my chiropractor and I am creating the API for data access.
I am creating a HttpPatch Method and want to know if this is the right approach so would be grateful if you could look over my code and let me know if I am doing it right, or if I need to change some things.
Patient Controller
[ValidateAntiForgeryToken]
[HttpPatch]
[Route("PatchPatient/{patientId:guid}")]
public async Task<IActionResult> PatchPatient([FromBody]Guid patientId, JsonPatchDocument<PatientModel> model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await _patient.PatchPatient(patientId, model);
return Ok(result);
}
PatientService
public async Task<JsonPatchDocument<PatientModel>> PatchPatient(Guid patientId, JsonPatchDocument<PatientModel> model)
{
var patient = await GetPatients(patientId);
var mappedPatientModel = _mapper.Map<Patient, PatientModel>(patient.FirstOrDefault());
model.ApplyTo(mappedPatientModel);
await _dbContext.SaveChangesAsync();
return model;
}
private async Task<List<Patient>> GetPatients(Guid? patientId)
{
var patients = await _dbContext.Patients.AsNoTracking().ToListAsync();
return patientId != null ? patients.Where(patient => patient.Id == patientId).ToList() : patients;
}
The idea of what I am trying to achieve is to update the patient record with the patch object that is going in.
Because I am doing this work in the service layer the model.ApplyTo(...) I cannot do a validation on the model state so unless I do a back and forth between controller and service I am not sure of the best approach and some guidance would be very much appreciated.