Controller

Controller plays main role in KambojaJS. It handles http request based on its generated route (url), then process separate view or response a JSON or XML body.

Route Generation

KambojaJS by default will generate route based on controller name, action (method) name and parameters name.

Controllers must be inherited from Controller base class.

import { Controller, view } from "kamboja-express"
 
export class ItemsController extends Controller {
    index(id:string) {
        return view()
    }
}

Above code will generate

GET items/index?id=<value>

Note you can override the behavior of route generating system if you’re not happy with the url generated, go to Http Decorator for more information.

Return Value

You can return any value that convertible to string, the value can be a promised value. All those value will be returned to client browser as a string with type text/html.

import { Controller } from "kamboja-express"
 
export class ItemsController extends Controller {
    index() {
        return "Hello World!"
    }

    promised(){
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve("Hello World!")
            }, 500)
        })
    }
}

From above code, both will render Hello World! if access from the browser, but the /items/promised will be delayed 500 ms.

Return ActionResult

For more advanced result, for example if you want to set response status, response header, sending cookie etc, you can return instance of derived class of ActionResult and set its appropriate property

Further more ActionResult have derived class that specialized to render view, doing redirection etc, read more on ActionResult.

import { Controller, view } from "kamboja-express"
 
export class ItemsController extends Controller {
    index(id:string) {
        //view() is short hand of new ViewActionResult()
        return view()
    }
}

Above code will render view based on view engine you are using.

Reading Http Request

It is recommended to use action parameters to get the request query string value, KambojaJS provide complete Http Request information in request property

import { Controller } from "kamboja-express"
 
export class ItemsController extends Controller {
    index(id:string) {
        let cookie = this.request.getCookie("my-cookie-name")
    }
}

Code above showing how you can access cookie from the HttpRequest. Complete field of HttpRequest object is below:

export interface HttpRequest {
    httpVersion: string
    httpMethod: HttpMethod
    headers: { [key: string]: string }
    cookies: { [key: string]: string }
    params: { [key: string]: string }
    user: any
    body: any
    referrer: string
    url: Url.Url
    getHeader(key: string): string
    getCookie(key: string): string
    getParam(key: string): string
    isAccept(mime: string): boolean
    isAuthenticated(): boolean
    getUserRole(): string
}