Skip to content

Instantly share code, notes, and snippets.

@adamcameron
Created October 9, 2022 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamcameron/c13b30d95ae79844c6602d0e62b5a3c6 to your computer and use it in GitHub Desktop.
Save adamcameron/c13b30d95ae79844c6602d0e62b5a3c6 to your computer and use it in GitHub Desktop.
This is the CFWheels controller I was building during my https://blog.adamcameron.me/2022/10/kotlin-tdd-writing-tests-for-small-web.html article
component extends=Controller {
function init() {
filters("getHeadersForRequest")
}
function getHeadersForRequest() {
variables.headers = getHttpRequestData().headers
}
function index() {
if (isPost()) {
return handlePost()
}
return handleGet()
}
function handleGet() {
if (variables.headers?.Accept does not contain "application/json") {
return handleNotAcceptable()
}
var numbers = [
{"id" = 1, "en" = "one", "mi" = "tahi"},
{"id" = 2, "en" = "two", "mi" = "rua"},
{"id" = 3, "en" = "three", "mi" = "toru"},
{"id" = 4, "en" = "four", "mi" = "wha"}
]
return renderJson(numbers)
}
function handlePost() {
var body = deserializeJson(GetHttpRequestData().content)
var location = urlFor(controller="Numbers", key=5, onlyPath=false).replace("/index", "")
return handleCreated(body, location)
}
function handleCreated(body, location) {
header statuscode="201" statustext="Created";
header name="Location" value=location;
return renderJson(body)
}
function handleNotFound() {
header statuscode="404" statustext="Not Found";
return renderJson({
"url" = CGI.path_info
})
}
function handleNotAcceptable() {
header statuscode="406" statustext="Not Acceptable";
return renderJson(["application/json"])
}
function renderJson(object) {
header name="Content-Type" value="application/json";
return renderText(serializeJson(object))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment