Skip to content

Latest commit

 

History

History
138 lines (103 loc) · 3.21 KB

controller.md

File metadata and controls

138 lines (103 loc) · 3.21 KB

Controller

back

Table of Contents

Creating a Controller

Use ducere command
ducere make controller

Resource controllers are controllers that have basic CRUD / resource style methods to them.
Generated controller is resource controller.

from strutils import parseInt
# framework
import basolato/controller


type SampleController* = ref object of Controller

proc newSampleController(request:Request):SampleController =
  return SampleController.newController(request)


proc index*(this:SampleController):Response =
  return render("index")

proc show*(this:SampleController, idArg:string):Response =
  let id = idArg.parseInt
  return render("show")

proc create*(this:SampleController):Response =
  return render("create")

proc store*(this:SampleController):Response =
  return render("store")

proc edit*(this:SampleController, idArg:string):Response =
  let id = idArg.parseInt
  return render("edit")

proc update*(this:SampleController):Response =
  return render("update")

proc destroy*(this:SampleController, idArg:string):Response =
  let id = idArg.parseInt
  return render("destroy")

Constructor & DI

main.nim

routes
  get "/": newSampleController(request).index()

app/controllers/sample_controller.nim

type SampleController = ref object of Controller

proc newSampleController*(request:Request): SampleController =
  return SampleController.newController(request)

proc index*(this:SampleController): Response =
  this.request # Request
  this.auth # Auth

When you define controller object extends Controller, request and auth is initialized.

Response

Returning string

If you set string in render proc, controller returns string.

return render("index")

Returning HTML file

If you set html file path in html proc, controller returns HTML.
This file path should be relative path from resources dir

return render(html("sample/index.html"))

>> display /resources/sample/index.html

Returning template

Call template proc with args in render will return template

resources/sample/index.nim

import basolato/view

proc indexHtml(name:string):string = tmpli html"""
<h1>index</h1>
<p>$name</p>
"""

main.nim

return render(indexHtml("John"))

Returning JSON

If you set JsonNode in render proc, controller returns JSON.

return render(
  %*{"key": "value"}
)

Response status

Put response status code arge1 and response body arge2

return render(HTTP500, "It is a response body")

Here is the list of response status code available.
Here is a experiment of HTTP status code