7.3: Persisting Profile Changes

Now, instead of console.logging our changes, let's implement persisting our changes back to the database.

Adding UserForUpdate DTO

We need to create a new data transfer object to represent the data we are sending from our update form to the server.

In your .Models project, add a new class called UserForUpdate.cs inside of the User folder.

public class UserForUpdate
{
    public string Introduction { get; set; }
    public string LookingFor { get; set; }
    public string Interests { get; set; }
    public string City { get; set; }
    public string State { get; set; }
}

Add Method to the UserService

Add a method signature in the IUserService.cs class:

Task<bool> UpdateUser(int id, UserForUpdate userForUpdate);

In the UserService class, implement the new method:

public async Task<bool> UpdateUser(int id, UserForUpdate model)
{
    var user = await _context.Users
                        .FirstOrDefaultAsync(u => u.Id == id);

    user.Introduction = model.Introduction;
    user.LookingFor = model.LookingFor;
    user.Interests = model.Interests;
    user.City = model.City;
    user.State = model.State;

    return await _context.SaveChangesAsync() == 1;
}

Add UpdateUser() method and endpoint to the UsersController

In the UsersController.cs file, add a new HttpPut method for UpdateUser():

[HttpPut("{id}")]
public async Task<IActionResult> UpdateUser(int id, [FromBody]UserForUpdate userForUpdate)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

    var userFromRepo = await _userService.GetUser(id);

    if (userFromRepo == null)
        return NotFound($"User could not be found.");

    if (currentUserId != userFromRepo.Id)
        return Unauthorized();

    if (await _userService.UpdateUser(id, userForUpdate))
        return NoContent();

    throw new Exception($"Updating user failed on save.");
}

Testing

In Postman, send a Put request to /api/users/{id} - entering an appropriate id from your database (in the example I'm using 2103 - yours will likely be different). Don't forget to provide a fresh Bearer token from the user you are updating in the header.

You should get a 204 No Content response:

You can send a get request to the same endpoint to check that it has changed:

The changes should also be reflected in the Angular application:

We've tested the "happy path", let's test a couple of scenarios when something goes wrong.

First, let's try to update a user that doesn't exist. Send repeat the previous request, but change the id to something you know doesn't exist in your database.

You should get a 404 Not Found response with a body of "User could not be found."

Next, let's try to update a that is different from the one we have a token for. Change the id in the endpoint to another user's id:

You should get a 401 Unauthorized response.

Persisting Changes Made on the Client

In user.service.ts, add an updateUser() method:

updateUser(id: number, user: User) {
    return this._http.put(this.baseUrl + 'users/' + id, user);
}

In member-edit.component.ts, update the updateUser() method to use the UserService instead of console.logging:

updateUser() {
    this._userService.updateUser(this._authService.decodedToken.nameid, this.user).subscribe(next => {
        this._alertify.success('Profile updated successfully.');
        this.editForm.reset(this.user);
    }, error => {
        this._alertify.error(error);
    });
}

Test it out in the browser. You should be able to update profile fields, save them, and see that the changes have persisted.

Last updated