Preparing the controller and routes

Similar to the UsersController.swift file, we can start by filling out the rough structure of the classes.

Go through the following steps:

  1. Write the following lines into the Sources/App/Controllers/AddressesController.swift file:
import Fluent
import Vapor

final class AddressesController: RouteCollection {

func boot(routes: RoutesBuilder ) {
}

func addresses(_ request: Request)throws ->
EventLoopFuture<[AddressResponse]> {}

func create(_ request: Request)throws ->
EventLoopFuture<AddressResponse> {}

func update(_ request: Request)throws ->
EventLoopFuture<AddressResponse> {}

func delete(_ request: Request)throws ->
EventLoopFuture<HTTPStatus> {}
}

So far, this is almost identical to the UsersController class.

  1. Enter the following lines to register our routes in the boot function:
 routes.get("", use: addresses)
routes.post("", use: self.create)
routes.patch(":id", use: self.update)
routes.delete(":id", use: delete)

Just as before, the base route (/*/users/addresses) is already given to this function, so we don't have to write all this down. You should be very familiar with the first two lines and understand what they do.

The third and fourth lines are adding a new element: :id

When you write down the paths for a route, you have done this so far by just writing it as a string, such as users. Technically, you can specify a path in a few different ways, though. One way is to supply a PathComponent of a RouteComponent. That could look like this:

router.get("a/b/:id", use: func) // "/a/b/:id"

Any class that conforms to a Parameter can be used as a RouteComponent. In our case, we simply want to pass on the ID of the address, so the parameter is of the type Int.

You might wonder how it is possible that both routes result in the same URL. Remember that it is always tied to the HTTP method. We are registering the routes for PATCH as well as DELETE. The URL itself would not be able to be called without specifying the HTTP method. However, we often tend to assume that it is a GET call, if not specified otherwise.

Okay—now, let's fill out the functions.

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

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