Grouping related routes

You'll find it convenient to group all routes for JournalController together. Vapor actually offers route grouping exactly for that.

Add the following route handlers to the JournalRoutes struct in the /Sources/App/Routes/JournalRoutes.swift file you've just created:

import Vapor

struct JournalRoutes : RouteCollection {

let journal = JournalController()

func boot(router: Router) throws {

let topRouter = router.grouped("journal") // [1]
topRouter.get(use: getTotal)
topRouter.post(use: newEntry)

let entryRouter = router.grouped("journal", Int.parameter) // [2]
entryRouter.get(use: getEntry)
entryRouter.put(use: editEntry)
entryRouter.delete(use: removeEntry)
}

// Add route handlers here // [3]

The JournalRoutes struct lays out two groups of routes, as follows:

  1. It creates the route group /journal for routes that retrieve all entries with HTTP GET and posts a new entry with HTTP POST
  2. It creates the second route group, /journal/Int.parameter, for routes that retrieve an entry with HTTP GET, updates an entry with HTTP UPDATE, and removes an entry with HTTP DELETE
  3. It adds all the required route-handler functions right after the boot(router:) function

The first route group in [1] tells Vapor to direct all URL requests to /journal, while the second group in [2] directs all requests to /journal/Int.parameter itself. The path, Int.parameter, is a dynamic parameter. The closures in a route group can access this dynamic parameter using req.parameters.next().