Delete

It happens: users may want to delete their account, as sad as it is. And if they do, we want to make sure they can do so correctly. For our case here, we need to delete two types of models: the addresses attached to the user, and the user itself.

  1. Let's grab the user as we did before, then write down the following line in the delete function:
return User.query(on: request.db).filter(.$id == request.payload.id).first().flatMap { user in
}

Now, we need to collect all addresses and delete them. Remember that we wrote a convenience function that allows us to grab addresses directly from the user model.

  1. Write down the following line after  { user:
if let user = user {
return Address.query(on: request.db).filter(
.$userId == user.id!).delete().flatMap {
return user.delete(on: request.db).
transform(to: .ok)
}
}
else {
return request.eventLoop.makeFailedFuture(
Abort(.badRequest, reason: "No user found!"))
}

This will delete all the addresses we found for the user. To get the instance back, we can add a .transform(to: user) to the line, and we will have an EventLoopFuture<User> instance again. Fluent allows us to delete a user from here on by simply adding .delete(on: request.db) to that future. And finally, we need to return an EventLoopFuture<HTTPStatus>, which we can do with transform again.

  1. Modify the line to look like this:
return user.delete(on: request.db).transform(to: .ok)

You can see how we are chaining various Fluent functions together that are all doing what we want them to. And that's it: the user is deleted now.

We are using the Fluent soft delete, which means the models are still in the database but are marked as deleted. If you want to change that so that they are deleted, just modify delete() to delete(force: true).

Alright—we have now finished all functions for the UsersController. Let's deal with address management next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.249.178