Barefoot.APIAdapter.Server

The server mixin for the APIAdapter takes the specified apiRoutes and does two things:

  • Create RESTful API routes with Express.JS, callable via HTTP
  • Map server-side API calls to the correct local callback

The creation of the Express.JS routes is done on initialization.  The mapping of server-side API calls is executed during runtime.

Function Mapping

The following matrix describes which function of APIAdapter.Server is related to which task:

                         + REST API + Local API +
+------------------------+----------+-----------+
 processCallbacks        |    X     |     X     |
 createExpressJsCallback |    X     |           |
 createExpressJsRoute    |    X     |           |
 urlRegexp               |          |     X     |
 matchRoute              |          |     X     |
 addRoute                |    X     |     X     |
 createRouteFactories    |    X     |     X     |
 dispatchLocalApiCall    |          |     X     |
 sync                    |          |     X     |
+------------------------+----------+-----------+
Summary
Barefoot.APIAdapter.ServerThe server mixin for the APIAdapter takes the specified apiRoutes and does two things:
Functions and Private Functions
toStringString representation of this module.
processCallbacksThis function is used to run a callback function or an array of stacked callback functions which are registered for an API route.
createExpressJsCallbackEncapsulates given callback function or an array with stacked callback functions and prepares it so it can be registered as an express js route.
createExpressJsRouteCreates an Express.JS request handlers.
urlRegexpTakes a route URL with possible placeholders like “/contacts/:contactid” and prepares a RegEx for later pattern matching when trying to resolve a route
extractParamsTakes a match object of a regex execution and extracts the parameters identified by keys.
matchRouteThis function takes an HTTP method and a URL.
addRouteThe functions generated by createRouteFactories use this function to create an actual api route.
createRouteFactoriesThis is called by the constructor of APIAdapter and is heavily inspired by the fancy Express.JS Application API.
dispatchLocalApiCallThis is the core where server side API callbacks are dispatched.
syncDuring startup on the server, this function replaces Backbones own sync implementation to shortcut “local” API calls.

Functions and Private Functions

toString

function toString()

String representation of this module.

processCallbacks

This function is used to run a callback function or an array of stacked callback functions which are registered for an API route.

Parameters

(Object) namedRouteParametersIf a route contains named parameters (stuff like “:id”, “:name”), this object should contain these values.  They are passed as arguments to each callback function.
(Object) dataThe data argument contains any larger data amount.  Stuff like the body of a POST request in example.
(Object) reqExpressJS request object is needed for creating scope objects for callback execution
(Object) resExpressJS response object is needed for creating the scope object for calling the handler functions.
(Function) successHandlerA function which is injected as the first argument when executing the callback
(Function) errorHandlerA function which is injected as the second argument when executing the callback
(Function)/(Array) callbacksAn API function which should be executed.  If you pass an array with functions, each function gets executed as it is stacked upon the array.  Calling success will proceed, error will stop execution.  Make sure you call one of them or your code will go nuts.

createExpressJsCallback

function createExpressJsCallback(successHandler,
errorHandler,
callbacks)

Encapsulates given callback function or an array with stacked callback functions and prepares it so it can be registered as an express js route.

The two functions successHandler and errorHandler are passed to the callback on runtime as the first two arguments.

Parameters

(Function) successHandlerA function which is injected as the first argument when executing the callback
(Function) errorHandlerA function which is injected as the second argument when executing the callback
(Function)/(Array) callbacksAn API function which should be executed.  If you pass an array with functions, each function gets executed as it is stacked upon the array.

Returns

(Function) to be registered with express js.

See also

createExpressJsRoute

Creates an Express.JS request handlers.

It takes an object containing route URI’s like “/contacts” or “/contacts/:name” as key and callback functions as values.  Using the passed Express.JS route-creation-function “binder” (app.post, app.put etc.), an Express.JS route is created.

Each route callback is wrapped into an Express.JS specific handler function connected to the route URI.  Combined with the Express.JS body parser middleware, the first argument of your callback will contain the body of the request.  If your route defines any parameters (“/contacts/:id”), the specific values are passed as function arguments.  If the request specifies any query parameters (“/contacts?message=test&limit=1”), you’ll find an object literal containing all these key-value pairs at the end of your callback arguments list.

Beside the return value of the callback, the wrapper function sends automatically an HTTP OK (200) to the request creator.  If the callback throws an error object, that object is inspected for an “httpStatusCode” property.  If present, that status code is delivered to the requestor.  If not, an HTTP Internal Server Error (500) is sent.

For a set of errors with predefined HTTP status codes, see Barefoot.Errors.

Parameters

(Object) urlURL route to bind
(Function)/(Array) callbacksAn API function which should be executed.  If you pass an array with functions, each function gets executed as it is stacked upon the array.
(Function) expressJsMethodA function of Express.JS like app.get etc.
(Object) appThe Express.JS app

See also

urlRegexp

Takes a route URL with possible placeholders like “/contacts/:contactid” and prepares a RegEx for later pattern matching when trying to resolve a route

Thanks to

Parameters

(String) urlThe url pattern to create the regex of
(Array) keysAn array which will contain all identified placeholder names afterwards
(Boolean) sensitiveCreate Regex case sensitive?
(Boolean) strictCreate Regex in strict mode?

Returns

(Regexp)

extractParams

Takes a match object of a regex execution and extracts the parameters identified by keys.  All values are returned inside an array at the end.

Thanks to

(Object) matchResulting match object of an executed Regexp
(Object) keysKeys to extract
(Object) paramsAn object which will contain all extracted parameters from url, if a route matched.

matchRoute

This function takes an HTTP method and a URL.  It tries to match any API route contained in apiRoutes.  If a route is found, the routes regex is used to extract any parameters from the URL.  These parameters are contained in the params argument afterwards.

The actual matched route gets returned if found.

Thanks to

Parameters

(String) methodAn HTTP method verb
(String) urlThe URL to match a route for
(Object) apiRoutesAn object containing all api routes too look after
(Object) paramsAn object which will contain all extracted parameters from url, if a route matched.

Returns

(Object) containing all information about the matched api route.  Dont forget that the params argument will contain any extracted parameters from the url!

addRoute

The functions generated by createRouteFactories use this function to create an actual api route.

To accomplish this, this creates a concrete Express.JS route which can be reached via REST HTTP.  To make the route callable locally, it gets saved into the apiRoutes variable.

Parameters

(String) methodThe HTTP method for this route
(String) urlThe URL for this route.  Gets prepared with <prepareAPIUrl>
(Function)/(Array) callbacksAn API function which should be executed.  If you pass an array with functions, each function gets executed as it is stacked upon the array.

createRouteFactories

function createRouteFactories()

This is called by the constructor of APIAdapter and is heavily inspired by the fancy Express.JS Application API.

It creates a function for each available HTTP method and makes it available through the APIAdapter itself.

These functions then can be used to create an APIAdapter route.

Example

apiAdapter.get('/myroute', function myCallback(success) { success(); });
apiAdapter.post('/myroute', function myCallback(success) { success(); });
// any HTTP verb :)

dispatchLocalApiCall

function dispatchLocalApiCall(httpMethod,
url,
data,
options)

This is the core where server side API callbacks are dispatched.  It is called by Barefoots sync replacement.

It tries to match the given URL with a registered route for the given httpMethod.  If found, the route callback(s) is/are invoked using processCallbacks.

If the data argument contains any information, that stuff gets passed to the callback.  If the options argument contains a success or error element, these functions are called by the callback in case of success or failure.

Example Call

dispatchLocalApiCall('post', '/contacts', { name: foo }, {
    success: function() { console.log('yay!'); }
    , error: function() { console.log('nay :('); }
});

Parameters

(String) httpMethodAn HTTP verb.  Necessary to match a registered route.
(String) urlThe URL of the API callback to dispatch
(Object) dataOptional.  Contains information which should be passed to the callback.  (Example: Contact information which should be saved.)
(Object) optionsShould contain an error and success callback function.

sync

function sync(method,
model,
options)

During startup on the server, this function replaces Backbones own sync implementation to shortcut “local” API calls.

Instead going the detour over an AJAX request, this implementation of sync calls the API callback directly by resolving the models URL with the present apiRoutes.

If method is not equal to read or delete, the return value of the toJSON function of the given model is passed to the API callback.

Parameters

(String) methodA method (create, update, patch, delete or read) which will be used to resolve the models URL properly.
(Backbone.Model) modelThe model which wants to be synced.  Can also be an instance of Backbone.Collection.
(Object) optionsShould contain at least a success callback.  Any api callback result will be delivered as argument of the success function.
When building a fancy JavaScript based client you’ll probably have a straight forward REST API in the backend.
function toString()
String representation of this module.
function createExpressJsCallback(successHandler,
errorHandler,
callbacks)
Encapsulates given callback function or an array with stacked callback functions and prepares it so it can be registered as an express js route.
function createRouteFactories()
This is called by the constructor of APIAdapter and is heavily inspired by the fancy Express.JS Application API.
function dispatchLocalApiCall(httpMethod,
url,
data,
options)
This is the core where server side API callbacks are dispatched.
function sync(method,
model,
options)
During startup on the server, this function replaces Backbones own sync implementation to shortcut “local” API calls.
The server mixin for the APIAdapter takes the specified apiRoutes and does two things:
This function is used to run a callback function or an array of stacked callback functions which are registered for an API route.
This class contains a set of predefined error objects which are thought to be used in your API route callbacks.
Close