Skip to content

Controllers

Hugo Persson edited this page Nov 21, 2020 · 4 revisions

Controllers


Every controller should be placed inside the controller directory and the filename should be path+"Controller" so for example the path /Dashboard/something would lead to a a file in the Controller directory with the name DashboardController.ts. In the file a class that extends Controller should be exported as default. The name of the class is irrelevant

Boilerplate code

import Controller from "@lib/Controller";

export default class Users extends Controller {}

Example controller

import Controller from "@lib/Controller";

export default class Users extends Controller {
    index() {
        // Index route for the controller
        // Route for this example is Users/
    }

    create() {
        // Called whenever the user enters the path Users/create
    }

    Create() {
        // actions are case sensitive so this method is called whenever the user enters the path Users/Create not Users/create
        // This is not recommended cause because it goes against typescript style guide
    }

    edit() {
        // example of how to use res
        this.res.send("Hello world");
    }
}

Request object


The request object is defined in the Controller and can be accessed with

this.req

Properties

Query string

Query strings are parsed and stored in the property queryStrings

// for the path /Dashboard/doSomething?name=Hugo&age=18
console.log(this.req.queryStrings);
// Would output
{
    name:"Hugo",
    age:"18"
}

Params

Params are parsed by the pattern: /name/value/ meaning that if you would like to pass the id and name for a user you would use the following path /Dashboard/doSomething/name/Hugo/id/4.

// for the path /Dashboard/doSomething/name/Hugo/id/4 
console.log(this.req.params);
// Would output
{
    name:"Hugo",
    age:"18"
}

Response object


Clone this wiki locally