Creating addresses

To create an address, we will have to get the authorized user first, then build the new address, and then save it.

Go through the following steps:

  1. Write the following line into the create function:
let content = try request.content.decode(AddressInput.self)

This should be very familiar to you by now; we are simply parsing the incoming content.

  1. Next, build the address, like this:
let address = Address(street: content.street, city: content.city,
zip: content.zip, userId: request.payload.id)

Remember that Vapor already ensured that the user content passed on is conforming to AddressInput.

While Vapor is making sure that the content of our input is matching our struct, Vapor does not know specific rules. If you wanted to make sure that a ZIP code is at least five digits long, you would need to enter that in the controller.
  1. Finally, we need to save the address and return the UserSuccessResponse, as follows:
return address.save(on: request.db).map { _ in
return AddressResponse(address)
}

And that's it! Easy, right? Now, let's move on to the next function: Update Address

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

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