Skip to content

Instantly share code, notes, and snippets.

@timmaybrown
Created September 24, 2014 18:08
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 timmaybrown/b7f33420b782497c848f to your computer and use it in GitHub Desktop.
Save timmaybrown/b7f33420b782497c848f to your computer and use it in GitHub Desktop.
ColdBox REST API: Example BaseRemoteHandler.cfc
component {
property name="customJSON" inject="model";
public void function preHandler(event, rc, prc){
prc["ret"] = {};
}
public any function onError(event, faultAction, exception, eventArguments){
//duplicate the PRC so it can be useful information during development
var prevPRC = duplicate(prc);
//make the ERROR ret based on the exception data
var stArgs = {
"event" = event
,"ret" = {
"msg" = arguments.exception.message
,"detail" = arguments.exception.detail
,"error" = {
"tagContext" = arguments.exception.tagContext
}
,"prcBeforeError" = prevPRC
}
,"statusCode" = 500
,"statusText" = "Application Error Occurred"
};
//send to the render results function to do the actual rendering out
renderResults(argumentCollection=stArgs);
}
public any function postHandler(event, rc, prc){
if (!event.valueExists("format") || (event.valueExists("format") && rc.format NEQ 'html')) {
//prep the renderResults argument collection
var stArgs = {
"event" = event
,"ret" = prc.ret
};
//if status code or status text are provided lets append those to the renderData() call
if (structKeyExists(prc, "statusCode")) stArgs.statusCode = prc.statusCode;
if (structKeyExists(prc, "statusText")) stArgs.statusText = prc.statusText;
//send to the render results function to do the actual rendering out
renderResults(argumentCollection=stArgs);
}
}
private any function renderResults(event, required any ret, numeric statusCode, string statusText){
// renderData() argument collection
//writeDump(GetComponentMetaData("model.apiKey").properties);abort;
var stArgs = {
"type" = "plain"
,"contentType" = "application/json"
,"data" = customJSON.serialize(input=ret)
};
//add statusCode and statusText to argCollection if one was specified explicitly
if (structKeyExists(ARGUMENTS, "statusCode")) stArgs.statusCode = ARGUMENTS.statusCode;
if (structKeyExists(ARGUMENTS, "statusText")) stArgs.statusText = ARGUMENTS.statusText;
//finally render it out
event.renderData(argumentCollection=stArgs);
}
private struct function badRequest(required string msg, string detail=""){
prc["statusCode"] = 400;
prc["statusText"] = "Unprocessable Entity";
prc["ret"] = {
"msg" = msg
,"detail" = detail
};
return prc;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment