Controllers

A controller is where the magic happens on each request since all routes have a controller attached to them. A controller can be as simple as rendering a template to as complex as processing lots of data from a database, file, resource or anything else you can think-up really.

Controller File

A controller file is a file located somewhere within the /app/controllers directory of your project. This file can be in sub-folders to make the directory structure easier to read.

The controller file can be structured in two different ways, each way is supported by the horsepower server.

  1. Class based – contains methods and a single exported class
  2. Function based – contains multiple exported functions

Note: All controllers can optionally be asynchronous if needed.

Class Based

A class based controller file exports a single class, with each method as a controller. When the route is accessed the class is instantiated, and the requested method is executed.

module.exports = class {
  async main(client) {
    // Controller body
  }

  async secondController(client) {
    // Controller body
  }
}

Function Based

A function based controller file exports multiple functions where each function is a controller. When the route is accessed nothing is instantiated, and the requested function is executed.

module.exports.main = async function(client) {
  // Controller body
}

module.exports.secondController = async function(client) {
  // Controller body
}

Resource Controller

A resource controller is nothing special, other than that it's methods/functions are predefined and relate to a route (See Route Resources for more information on the routing aspect).

A full resource controller will contain all of the following methods (All of which are optional based on the ones you need).

module.exports = class {
  async main(client) { }
  async create(client) { }
  async store(client) { }
  async show(client) { }
  async edit(client) { }
  async update(client) { }
  async destroy(client) { }
}