Using Vapor's route collection

Vapor allows you to use route collection in managing the collection of related routes. With route collection, you can divide your routes and let one sub-router that implements RouteCollection protocol handle a segment of routes. Each sub-router doesn't need to handle all routes, as it is responsible for the routes that it can handle only.

In /Sources/App/routes.swift, instantiate a RouteCollection and register it with the router:

import Vapor

/// Register your application's routes here
public func routes(_ router: Router) throws {

let journalRoutes = JournalRoutes()
try router.register(collection: journalRoutes)
}

Create the Routes directory under /Sources/App and add JournalRoutes.swift to this new directory:

// JournalRoutes.swift
import Vapor

struct JournalRoutes : RouteCollection { // [1]

let journal = JournalController() // [2]

func boot(router: Router) throws { // [3]
// to be implemented later
}
// Add route handlers here // [4]
}

All the routes and their handlers will go to this new file. The JournalRoutes struct does several things:

  1. Implements the RouteCollection protocol
  2. Creates an instance of JournalController that works with in-memory persistence
  3. Adds the boot(router:) function to for one-time set up. Routes will be implemented here
  4. Adds the rest of the route handlers right after the boot(router:) function

Even though the implementation of RouteCollection is straightforward, it is extremely useful for organizing your routes into different functional areas. For example, you may want to use RouteCollection to conveniently designate user access level to different content areas.