-
Notifications
You must be signed in to change notification settings - Fork 1
Controllers
Web requests are routed through routes.js to a controller action. Nexi provides a simple interface do define controllers and actions that can be easily referenced in the routes file.
Controllers should reside in the src/app/controllers/
directory, or any subdirectory within it. A controller's filename must kebab case (my-file-name.js) ending in -controller.js
. Example: home-page-controller.js
A controller is a class that inherits from nexi's BaseController. Any public function can be referenced as a controller action by a route. The file must export the controller class as the default export.
// src/app/controllers/home-page-controller.js
const { BaseController } = require('nexi')
class HomePageController extends BaseController {
async welcome(req, res) {
const user = this.context.models.users.findOne({ id: req.params.id })
return res.render('home/welcome', { user } )
}
}
module.exports = HomePageController
By inheriting from BaseController, your controller has access to the application context, and eventually some helpful control flow functions.
All controller actions will be passed an instance of the express request object. You can use this object to access any inbound request data such as url params (req.params
), query string parameters (req.query
), json/form request bodies (req.body
), etc.
By default nexi applications are packaged with a templating engine, so nexi controllers are able to render a view using express-handlebar's render method.
Along with views, your controller can call and return any express response method to return the correct response/response type.