1
\$\begingroup\$

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.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

In general the patch endpoint should consist of the following steps (order is important):

  1. Preliminary check(s) (for example in case of null return BadRequest)
  2. Load existing object (based on the request's key)
  3. Apply the existing object (if any) onto the patch request
  4. Validate model state (and return BadRequest if it is ain't valid)
  5. Save changes
  6. Return with appropriate status code

I would suggest to check the corresponding error handing.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.