Controller

Moduleejs.web
Definition class Controller
InheritanceController inherit Object
Specifiedejscript-2.5
StabilityPrototype.

Web framework controller class.

The Controller class is part of the Ejscript Model View Controller (MVC) web framework. Controller class instances can accept web requests and direct them to action methods for servicing which generates the response. Controllers are responsible for either generating output for the client or invoking a View which will create the response. By convention, all Controllers should be defined with a "Controller" suffix. This permits similar Controller and Model classes to exist in the same namespace.

Action methods will autoFinalize by calling Request.autoFinalize unless Request.dontAutoFinalize has been called. If the Controller action wants to keep the request connection to the client open, you must call dontAutoFinalize before returning from the action.


Properties

QualifiersPropertyTypeDescription
get absHomeUriUri for the top-level of the application. This is an absolute Uri that includes scheme and host components. See home to get a relative Uri.
actionNameStringName of the Controller action method being run for this request.
get autoFinalizingBooleanControl whether auto-finalizing will be used for the request. If autoFinalizing is false, a request must call finalize() to signal the end of write data. If autoFinalize is true, the Request class will automatically call finalize at the conclusion of the request. Applications that wish to keep the request open to the client can suppress auto-finalization by setting autoFinalizing to false or by calling dontAutoFinalize(). This property defaults to true.
cacheIndexStringnull
cacheItemObjectnull
cacheNameStringnull
cacheOptionsObjectnull
configObjectConfiguration settings. This is a reference to Request.config.
controllerNameStringPascal case controller name.
logLoggerLogger stream - reference to Request.log.
get finalizedBooleanHas the request output been finalized.
get homeUriHome URI for the application. This is a relative Uri from the current URI to the the top-most directory level of the application.
get flashObjectNotification "flash" messages to pass to the next request (only). By convention, the following keys are used. error: Negative errors (Warnings and errors), inform: Informational / postitive feedback (note), warn: Negative feedback (Warnings and errors), *:: Other feedback (reminders, suggestions...).
paramsObjectForm and query parameters. This is a reference to the Request.params object.
get pathInfoStringLocation of the request within the application.0. This is the portion of the request URL after the scriptName. The pathInfo is originally derrived from uri.path after splitting off the scriptName. Changes to the uri or scriptName properties will not affect the pathInfo property.
get sessionSessionSession state object. The session state object can be used to share state between requests. If a session has not already been created, accessing this property automatically creates a new session and sets the Request.sessionID property and a cookie containing a session ID sent to the client with the response. To test if a session has been created, test the sessionID property which will not auto-create a session. Objects are stored in the session state using JSON serialization.
requestRequestReference to the current Request object.
get uriUriThe current request URI. This property is read-only and is dynamically computed from the originalUri combined with the current scheme, host, port, scriptName, pathInfo, query and reference property values. The "uri" property has fields for: scheme, host, port, path, query and reference.

Controller Class Methods

QualifiersMethod
static cache(controller, actions: Object, options: Object = expression): Void
 Controler action caching.
static create(request: Request, cname: String = null): Controller
 Static factory method to create and initialize a controller.
static updateCache(controller, actions: Object, data: Object, options: Object = expression): Void
 Update the cache contents.

Controller Instance Methods

QualifiersMethod
Controller(req: Request = null)
 Create and initialize a controller.
after(fn, options: Object = null): Void
 Run an check function after running the action.
app(request: Request, aname: String = null): Object
 Controller web application.
autoFinalize(): Void
 Finalize the request if autoFinalizing is true.
before(fn, options: Object = null): Void
 Run an action checker before running the action.
clearFlash(): Void
 Clear previous flags messages.
dontAutoFinalize(): Void
 Stop auto-finalizing the request.0.
error(msg: String): Void
 Set an error flash notification message.
finalize(): Void
 Signals the end of any and all response data and flushes any buffered write data to the client.(.
link(target: Object): Uri
 Create a URI link.
flush(dir: Number): Void
 Flush the stream and underlying streams.Flush request data.
header(key: String): String
 Get a request header by keyword.
inform(msg: String): Void
 Set an informational flash notification message.
action missing()
 Missing action method.
notify(key: String, msg: String): Void
 Set a transient flash notification message.
on(name, observer: Function): Controller
 Add an observer to the stream for the named events.
read(buffer: ByteArray, offset: Number, count: Number = -1): Number
 Read a data from the stream.If the request is posting a form, i.e.
redirect(where: Object, status: Number = expression): Void
 Redirect the client to the given URL.
removeCheckers(): Void
 Remove all defined checkers on the Controller.
setStatus(status: Number): Void
 Convenience routine to set the (proposed) Http response status code.
setHeader(key: String, value: String, overwrite: Boolean): Void
 Convenience routine to set a Http response header in responseHeaders.
setHeaders(headers: Object, overwrite: Boolean): Void
 Convenience routine to set multiple Http response headers in responseHeaders.
warn(msg: String): Void
 Set a warning flash notification.
write(args: Array): Number
 Low-level write data to the client.
writeCached(): Boolean
 Manually write out cached content to the client.
writeContent(data): Void
 TODO - DEBUG Write content based on the requested accept mime type.
writeError(status: Number, msgs: Array): Void
 Render an error message as the response.
writeFile(filename: Path): Void
 Render file content back to the client.
writePartialTemplate(path: Path, options: Object = expression): Void
 Render a partial response using template file.
writeTemplate(path: Path, options: Object = expression): Void
 Render a view template from a path.
writeTemplateLiteral(page: String, options: Object = expression): Void
 Render a view template from a string literal.
writeView(viewName = null, options: Object = expression): Void
 Render a view template.

Method Detail

ejs.web Controller(req: Request = null)
Description
Create and initialize a controller. This may be called directly or via the Controller.create factory method.
Parameters
req: Request Web request object 8. [default: null]

ejs.web after(fn, options: Object = null): Void
Description
Run an check function after running the action.
Parameters
fn Function callback to invoke.
options: Object Check function options. [default: null]
Options
only[String|Array] Only run the checker for this action name. This can be a string action name or an array of action names.
except[String|Array] Run the check function for all actions except this name. This can be a string action name or an array of action names.

ejs.web app(request: Request, aname: String = null): Object
Description
Controller web application. This function will run a controller action method and return a response object. The action method may be specified by the aname parameter or it may be supplied via Request.params.action.
Parameters
request: Request Request object.
aname: String Optional action method name. If not supplied, params.action is consulted. If that is absent too, "index" is used as the action method name. [default: null]
Returns
A response object hash {status, headers, body} or null if writing directly using the request object.

ejs.web autoFinalize(): Void
Description
Finalize the request if autoFinalizing is true. Finalization signals the end of any write data and flushes any buffered write data to the client. This routine is used by frameworks to finalize requests if required.

ejs.web before(fn, options: Object = null): Void
Description
Run an action checker before running the action. If the checker function writes a response, the normal processing of the requested action will be prevented. Note that checkers do not autoFinalize so if the checker does write a response, it must call finalize.
Parameters
fn Function callback to invoke.
options: Object Checker options. [default: null]
Options
only[String|Array] Only run the checker for this action name. This can be a string action name or an array of action names.
except[String|Array] Run the checker for all actions except this name This can be a string action name or an array of action names.

static cache(controller, actions: Object, options: Object = expression): Void
Description
Controler action caching. This caches the entire output of an action (including generated view). Caching is disabled/enabled via the ejsrc config.cache.actions.enable field. It is enabled by default. Caching may be used for any HTTP method, though typically it is most useful for state-less GET requests. Output data is uniquely cached for requests with different URI post data or query parameters.
Parameters
controller Controller class. This can be a Controller class object, "this" or a String controller name. You can specify "this" in static code or can also use "this" in class instance code and this routine will determine the underlying controller class.
actions: Object Action string or array of actions.
options: Object Cache control options. Default options for all action caching can be provided via the ejsrc config.cache.actions field. This is frequently used to specifiy a default lifespan for cached data. [default: expression]
Options
modeClient caching mode. Defaults to "server" if unset. If mode is set to "client", a Cache-Control header will be sent to the client with the caching "max-age" set to the lifespan. This causes the client to serve client-cached content and to not contact the server at all until the max-age expires. If mode is set to "manual", the output from the action will be cached, but the action routine will always be called. To use the cached content in this mode, call writeCached() in the action method. The default mode is "server" which caches content at the server for the specified lifespan. In server mode, the client will cache requests, but will always revalidate the request with the server. If the server-side content has not expired, a HTTP Not-Modified (304) response will be given and the client will use its client-side cached content. Use "client" mode for static content that will rarely change and for which using "reload" in the browser is an adequate solution to force a refresh. Use "server" mode for dynamic content in conjunction with updateCache to expire or update cache contents. Use "manual" mode when the action routine needs to determine if cached content can be used on a case by case basis. If a client browser clicks reload, the client cached and server cached content will be ignored and the action method will be always invoked.
lifespanTime in seconds for the cached output to persist.
clientCache-Control header to send to the client to control caching in the client. Use this for explicit control of the Cache-Control header and thus control of caching in the client. This can be used to set a "max-age" for cached data in the client. These are some of the HTTP/1.1 Cache-Control keywords that can be used in the client option are: "max-age" Max time in seconds the resource is considered fresh. "s-maxage" Max time in seconds the resource is considered fresh from a shared cache. "public" marks authenticated responses as cacheable. "private" shared caches may not store the response. "no-cache" cache must re-submit request for validation before using cached copy. "no-store" response may not be stored in a cache. "must-revalidate" forces clients to revalidate the request with the server. "proxy-revalidate" similar to must-revalidate except only for proxy caches> // TODO - unclear, clarify.
uriURI and parameter to further differentiate cached content. If supplied, different cache data can be stored for each URI that applies to the given controller/action. If the URI is set to "*"" all URIs for that action/controller are uniquely cached. If the request has POST data, the URI may include such post data in a query format. E.g. {uri: /buy?item=scarf&quantity=1}.
Example
cache(DashController, "index", {lifespan: 200})
cache(this, ["index", "edit", "show"])
cache(this, "index", false)

ejs.web clearFlash(): Void
Description
Clear previous flags messages. Useful when using client mode caching for an action.
Stability
Prototype.

static create(request: Request, cname: String = null): Controller
Description
Static factory method to create and initialize a controller. The controller class is specified by params["controller"] which should be set to the controller name without the "Controller" suffix. This call expects the controller class to be loaded. Called by Mvc.load().
Parameters
request: Request Web request object.
cname: String Controller class name. This should be the name of the Controller class without the "Controller" suffix. X. [default: null]

ejs.web dontAutoFinalize(): Void
Description
Stop auto-finalizing the request.0. This will set autoFinalizing to false. Some web frameworks will "auto-finalize" requests by calling finalize() automatically at the conclusion of the request. Applications that wish to keep the connection open to the client can defeat this auto-finalization by calling dontAutoFinalize().

ejs.web error(msg: String): Void
Description
Set an error flash notification message. Flash messages persist for only one request and are a convenient way to pass state information or feedback messages to the next request. To use flash messages, setupFlash() and finalizeFlash() must be called before and after the request is processed. HttpServer.process will call setupFlash and finalizeFlash automatically.
Parameters
msg: String Message to store.

ejs.web finalize(): Void
Description
Signals the end of any and all response data and flushes any buffered write data to the client.(. If the request has already been finalized, this call has no additional effect.

ejs.web link(target: Object): Uri
Description
Create a URI link. The target parameter may contain partial or complete URI information. The missing parts are supplied using the current request and route tables. The resulting URI is a normalized, server-local URI (begins with "/"). The URI will include any defined scriptName, but will not include scheme, host or port components.
Parameters
target: Object The URI target. The target parameter can be a URI string or object hash of components. If the target is a string, it is may contain an absolute or relative URI. If the target has an absolute URI path, that path is used unmodified. If the target is a relative URI, it is appended to the current request URI path. The target can also be an object hash of URI components: scheme, host, port, path, reference and query. If these component properties are supplied, these will be combined to create a URI. The URI will be created according to the route URI template. The template may be explicitly specified via a "route" target property. Otherwise, if an "action" property is specified, the route of the same name will be used. If these don't result in a usable route, the "default" route will be used. See the Router for more details. If the target is a string that begins with " @" it will be interpreted as a controller/action pair of the form " @Controller/action". If the "controller/" portion is absent, the current controller is used. If the action component is missing, the "index" action is used. A bare " @" refers to the "index" action of the current controller. Lastly, the target object hash may contain an override "uri" property. If specified, the value of the "uri" property will be returned and all other properties will be ignored.
Options
schemeString URI scheme portion.
hostString URI host portion.
portNumber URI port number.
pathString URI path portion.
referenceString URI path reference. Does not include "#".
queryString URI query parameters. Does not include "?".
controllerString Controller name if using a Controller-based route. This can also be specified via the action option.
actionString Action to invoke. This can be a URI string or a Controller action of the form.
routeString Route name to use for the URI template.
Returns
A normalized, server-local Uri object. The returned URI will be an absolute URI.
Example
Given a current request of http://example.com/samples/demo" and "r" == the current request:

r.link("images/splash.png")                  # "/samples/images/splash.png"
r.link("images/splash.png").complete(r.uri)  # "http://example.com/samples/images/splash.png"
r.link("images/splash.png").relative(r.uri)  # "images/splash.png"

r.link("http://example.com/index.html")
r.link("/path/to/index.html")
r.link("\@Controller/checkout")
r.link("\@Controller/")
r.link("\@checkout")
r.link("\@")
r.link({action: "checkout")
r.link({action: "logout", controller: "Admin")
r.link({action: "Admin/logout")
r.link({action: "\@Admin/logout")
r.link({uri: "http://example.com/checkout"})
r.link({route: "default", action: "\@checkout")
r.link({product: "candy", quantity: "10", template: "/cart/{product}/{quantity}}")

ejs.web flush(dir: Number): Void
Description
Flush the stream and underlying streams.Flush request data. A supplied flush direction argument modifies the effect of this call. If direction is set to Stream.READ, then all read data is discarded. If direction is set to Stream.WRITE, any buffered data is written. Stream.BOTH will cause both directions to be flushed. If the stream is in sync mode, this call will block until all data is written. If the stream is in async mode, it will attempt to write all data but will return immediately. Defaults to Stream.WRITE.Calling flush(Sream.WRITE) or finalize() is required to ensure buffered write data is sent to the client. Flushing the read direction is ignored.
Parameters
dir: Number Direction to flush. Set to READ WRITE or BOTH.

ejs.web header(key: String): String
Description
Get a request header by keyword. Headers supplied by the remote client are stored in lower-case. Headers defined on the server-side preserve case. This routine supports both by doing a case-insensitive lookup.
Parameters
key: String Header key value to retrieve. The key match is case insensitive.
Returns
The header value.

ejs.web inform(msg: String): Void
Description
Set an informational flash notification message. Flash messages persist for only one request and are a convenient way to pass state information or feedback messages to the next request. To use flash messages, setupFlash() and finalizeFlash() must be called before and after the request is processed. HttpServer.process will call setupFlash and finalizeFlash automatically.
Parameters
msg: String Message to store.

action missing()
Description
Missing action method. This method will be called if the requested action routine does not exist. It should be overridden in user controller classes by using the "override" keyword.

ejs.web notify(key: String, msg: String): Void
Description
Set a transient flash notification message. Flash messages persist for only one request and are a convenient way to pass state information or feedback messages to the next request. To use flash messages, setupFlash() and finalizeFlash() must be called before and after the request is processed. HttpServer.process will call setupFlash and finalizeFlash automatically.
Parameters
key: String Flash message key.
msg: String Message to store.

ejs.web on(name, observer: Function): Controller
Description
Add an observer to the stream for the named events.
Parameters
name: [String|Array]Name of the event to listen for. The name may be an array of events.
observer: Function Callback observer function. The function is called with the following signature: function observer(event: String, ...args): Void.
Events
readableIssued when the stream becomes readable.
writableIssued when the stream becomes writable.
closeIssued when stream is being closed. 8.
writableIssued when the connection is writable to accept body data (PUT, POST).
closeIssued when the request completes.
errorIssued if the request does not complete or the connection disconnects. An error event is not caused by non-200 status codes, these are regarded as valid return results. Rather, an error event will be issued when the request cannot return a complete, valid Http response to the client. All events are called with the signature: function (event: String, http: Http): Void.

ejs.web read(buffer: ByteArray, offset: Number, count: Number = -1): Number
Description
Read a data from the stream.If the request is posting a form, i.e. If data is available, the call will return immediately. If no data is available and the stream is in sync mode, the call will block until data is available. If no data is available and the stream is in async mode, the call will not block and will return immediately. In this case a "readable" event will be issued when data is available for reading.the Http ContentType header is set to "application/x-www-form-urlencoded", then the request object will not be created by the HttpServer until all the form data is read and the params collection created and populated with the form data. This permits form data to be processed synchronously without having to use async/observer techniques to respond to readable events. With all other content types, the Request object will be created and run before the incoming client data has been read. To read data in these situations, register an observer function to run when the connection becomes "readable".
Parameters
buffer: ByteArray Destination byte array for read data.
offset: Number Offset in the byte array to place the data. If the offset is -1, then data is appended to the buffer write position which is then updated. If offset is >= 0, the data is read to the offset and the read pointer is set to the offset and the write pointer to one past the end of the data just read.
count: Number Read up to this number of bytes. If -1, read as much as the buffer will hold up. If the stream is of fixed and known length (such as a file) and the buffer is of sufficient size or is growable, read the entire stream. If the buffer is of a fixed size, ready only what will fit into the buffer. [default: -1]
Events
readableIssued when there is new read data available.
writableIssued when the stream becomes empty. `.
Returns
A count of the bytes actually read. Returns null on EOF or errors.
Example
request.on("readable", function(event, request) {
    var data = new byteArray
    if (read(data)) {
        print("Got " + data)
    } else {
        //  End of input, call finalize() when all output has been written
        request.finalize()
    }
})

ejs.web redirect(where: Object, status: Number = expression): Void
Description
Redirect the client to the given URL.
Parameters
where: Object Url to redirect the client toward. This can be a relative or absolute string URL or it can be a hash of URL components. For example, the following are valid inputs: "../index.ejs", "http://www.example.com/home.html", {action: "list"}.
status: Number Http status code to use in the redirection response. Defaults to 302. [default: expression]

ejs.web removeCheckers(): Void
Description
Remove all defined checkers on the Controller. 0.

ejs.web setStatus(status: Number): Void
Description
Convenience routine to set the (proposed) Http response status code. This is equivalent to assigning to the status property.

ejs.web setHeader(key: String, value: String, overwrite: Boolean): Void
Description
Convenience routine to set a Http response header in responseHeaders. If a header has already been defined and overwrite is true, the header will be overwritten. NOTE: case is ignored in the header keyword. Access responseHeaders to inspect the proposed response header set.
Parameters
key: String The header keyword for the request, e.g. "accept".
value: String The value to associate with the header, e.g. "yes".
overwrite: Boolean If the header is already defined and overwrite is true, then the new value will overwrite the old. If overwrite is false, the new value will be catenated to the old value with a ", " separator.

ejs.web setHeaders(headers: Object, overwrite: Boolean): Void
Description
Convenience routine to set multiple Http response headers in responseHeaders. Access responseHeaders to inspect the proposed response header set.
Parameters
headers: Object Set of headers to use.
overwrite: Boolean If the header is already defined and overwrite is true, then the new value will overwrite the old. If overwrite is false, the new value will be catenated to the old value with a ", " separator.

static updateCache(controller, actions: Object, data: Object, options: Object = expression): Void
Description
Update the cache contents. This will manually update the cache contents for the given actions with the supplied data. If data is null, then cached content will be immediately expired.
Parameters
controller Controller class. This can be a Controller class object, "this" or a String controller name. You can specify "this" in static code or can also use "this" in class instance code and this routine will determine the underlying controller class.
actions: Object Action string or array of actions.
data: Object Object data to cache. Data is serialized using JSON and stored in the cache. Set to null to invalidate/expire cached data.
options: Object Cache control options. [default: expression]
Options
uriURI and parameter to further differentiate cached content. If supplied, different cache data can be stored for each URI that applies to the given controller/action. If the URI is set to "*"" all URIs for that action/controller are uniquely cached. If the request has POST data, the URI may include such post data in a query format. E.g. {uri: /buy?item=scarf&quantity=1}.

ejs.web warn(msg: String): Void
Description
Set a warning flash notification. Flash messages persist for only one request and are a convenient way to pass state information or feedback messages to the next request. To use flash messages, setupFlash() and finalizeFlash() must be called before and after the request is processed. HttpServer.process will call setupFlash and finalizeFlash automatically.
Parameters
msg: String Message to store.

ejs.web write(args: Array): Number
Description
Low-level write data to the client. This will buffer the written data until either flush() or finalize() is called. If an action method does call a write data back to the client and has not called finalize() or dontAutoFinalize(), a default view template will be generated when the action method returns.
Parameters
args: Array Arguments to write to the client. The args are converted to strings.
Returns
The number of bytes written to the client.

ejs.web writeCached(): Boolean
Description
Manually write out cached content to the client. This routine will write non-expired cached data to the client. Caching for actions is enabled by calling cache() in the Controller.
Returns
True if valid cached content was found to write to the client.

ejs.web writeContent(data): Void
Description
TODO - DEBUG Write content based on the requested accept mime type.
Parameters
data Data to send to the client.

ejs.web writeError(status: Number, msgs: Array): Void
Description
Render an error message as the response. This call sets the response status and writes a HTML error message with the given arguments back to the client.
Parameters
status: Number Http response status code.
msgs: Array Error messages to send with the response.

ejs.web writeFile(filename: Path): Void
Description
Render file content back to the client. This call writes the given file contents back to the client.
Parameters
filename: Path Path to the filename to send to the client.

ejs.web writePartialTemplate(path: Path, options: Object = expression): Void
Description
Render a partial response using template file.
Parameters
path: Path Path to the template to render to the client.
options: Object Additional options. [default: expression]
Options
layoutOptional layout template. Defaults to config.dirs.layouts/default.ejs.

ejs.web writeTemplate(path: Path, options: Object = expression): Void
Description
Render a view template from a path. This call writes the result of running the view template file back to the client.
Parameters
path: Path Path to the view template to render and write to the client.
options: Object Additional options. [default: expression]
Options
layoutOptional layout template. Defaults to config.dirs.layouts/default.ejs.

ejs.web writeTemplateLiteral(page: String, options: Object = expression): Void
Description
Render a view template from a string literal. This call writes the result of running the view template file back to the client.
Parameters
page: String String literal containing the view template to render and write to the client.
options: Object Additional options. [default: expression]
Options
layoutPath layout template. Defaults to config.dirs.layouts/default.ejs.

ejs.web writeView(viewName = null, options: Object = expression): Void
Description
Render a view template. This call writes the result of running the view template file back to the client.
Parameters
viewName Name of the view to render to the client. The view template filename will be constructed by joining the views directory with the controller name and view name. E.g. views/Controller/list.ejs. [default: null]
options: Object Additional options. [default: expression]
Options
controllerOptional controller for the view.
layoutOptional layout template. Defaults to config.dirs.layouts/default.ejs.