yukon API framework
yukon is a component-based framework built on top of node/express - which processes 0-n REST APIs in parallel for each express request. It extends the nodulejs component framework.
"nodules" are self-discovering, self-initializing web components, which propagate throughout the express middleware chain as req.nodule. Nodulejs was split off from yukon to separate out the core self-discovery and initialization features. These potentially could be used as a building block for a wide variety of frameworks.
Installation
$ npm install yukon
Usage
require('yukon')(app, config);
- app = express instance.
- config = any custom properties you want to add or defaults you want to override. See the demoApp for an example of a working yukon app. See the Config section below more details on config options.
What is a yukon nodule?
A nodule is a self-discovering, self-initializing component that would be to a JSP or PHP page in those worlds. A yukon nodule extends the base nodule behavior to include REST API data gathering, stub-handling and template-rendering.
Unlike the PHP/JSP worlds however, a nodule's route is declared and not tied by default to the filename or folder structure. So you are free to re-organize nodules without upsetting urls. But more importantly, because nodules are self-discovering, there are no onerous config files to maintain (IE - Spring). This system allows a much more scalable architecture on large sites--as there are no config or other shared files which grow to enormous sizes as the site grows, and nodules can be re-organized with zero impact.
Motivation
From a feature-development point of view, we wanted to give developers the flexibility of component-based architecture as much as possible, but still keep system-wide control over the middleware chain. On a small site with a small development team the latter might not be an issue. But on a large site with devs scattered all over the globe, some kind of middleware sandbox was a necessity.
Our feature devs spend 80-90% of their effort in jade templates or on the client side. For them, node components are often just a pass-through to the API(s), with some business logic applied to the request on the way in, and api data on the way out. Ideally they should have to learn the as little as possible of the vagaries/plumbing/whatever-your-favorite-metaphor-for-framework-stuff of node. Creating a new node component should be as easy for them as creating a new JSP - but again, without the framework losing control of the middleware chain.
From a framework-development point of view, we knew that as requirements evolved, we would constantly need to add default properties to each component, while hopefully causing as little disruption as possible to existing components. This is easily accomplished by adding a default property to the base config, then specifying the property only in the nodules that need the new property.
We also knew we'd need to add slices of business logic globally or semi-globally at any point in the request chain. By keeping control of the middleware chain we are able to do this with ease.
This diagram might make the concept a little more clear:
Config
Yukon config is broken into 3 sections:
- Nodule-specific properties
- API-specific properties
- App-defined middleware functions and global settings
Note: You may occasionally see "MAGIC ALERT" below. This is for the handful of times where the framework does some convenience method that isn't immediately obvious, but comes up so much we felt the code saving was worth the loss in conceptual clarity.
Nodule-specific properties (config.noduleDefaults)
Yukon inherits the 4 core nodulejs defaults:
- route: (REQUIRED) one or more express routes - can be a string, RegExp, or array of either
- routeVerb: (OPTIONAL, default=get) get, post, put, del
- routeIndex: (OPTIONAL, default=0) use to match express routes before or after others, can be negative, like z-index
- middlewares: (OPTIONAL) define this in your nodule to override the entire yukon request chain. See 404.js from the demoApp for example.
Yukon also adds the following optional nodule properties:
- templateName: MAGIC ALERT: if null the framework looks for a template in the same folder and of the same name as the nodule filename + templateExt. So if you have myPage.jade in the same folder as myPage.js, there is no need to specify template name.
- templateExt: default template extension
- contentType: 'html' and 'json' are the only current values
- preProcessor: use this function to manipulate query params or other business logic before api call
- postProcessor: use this function to process data returned from the API before calling template or sending back to client as JSON
- error: set to a string or an Error() instance to get the framework to call next(error)
- apiCalls: array of API calls to made in parallel for this nodule, see the section below for details what constitutes an API call.
NOTE: global or semi-global calls like getProfile, getGlobalNav, etc. can be added to this array in the appPreApi middleware.
API-specific properties (config.apiDefaults)
Yukon defines the following properties for each API call. It is important to understand that these exist in a one-to-many relationship with nodules.
- path: path to API (not including server).
MAGIC ALERT: if the API path ends with a slash(/), the framework automatically tries to append req.params.id from the express :id wildcard. For us at least this is a very common REST paradigm. - params: params to send to API server. If the api verb is 'post', this can be a deep json object (bodyType=json) or a shallow object of name value pairs (bodyType=form).
- verb: get, post, put, del
- bodyType: valid values: json, form
- host: path to the API server, can be set in app-defined middleware or overridden at the nodule level.
- customHeaders: custom headers to sent with API call
- timeout: (numeric) - max API return time in ms
- useStub: set true to force framework to use stub instead of API
- stubPath: can contain path or just name if in same folder
MAGIC ALERT: if not specified, app looks for [nodule name].stub.json in nodule folder
App-defined middlware
An app can create and use 4 optional express middleware functions, which splice in between the built-in yukon middleware (see yukon.js for more detail):
- appStart: called at start of middleware, before nodule.preProcessor
- appPreApi: called after nodule.preProcessor, before API call(s)
- appPostApi: called after API call(s), before nodule.postProcessor
- appFinish: called after nodule.postProcessor, before res.send() or res.
An app can also create 2 global functions, which are executed before and after every API call. It's important to understand that there can be several API calls per express request. So these functions are not in the standard middleware chain, although the api callback does make use of the middleware paradigm.
- apiCallBefore: a synchronous function executed before of every api call. Do any common API pre-processing here.
- apiCallback: an asynchronous function executed after every api call, must execute next() if defined. Do error handling and other common post-API processing here.
Global properties
There are also 3 global config properties inherited from nodulejs:
- dirs: (OPTIONAL, default='/nodules') path(s) to look for your nodules, exclude property can be full or partal match
example: [{ path: '/app', exclude: ['demoApp.js', '.test.js', '/shared/'] }, { path: '/lib/nodules', exclude: ['.test.js'] }] - debugToConsole: (OPTIONAL, default=false) set to true to see nodulejs debug output in the console
- customDebug: (OPTIONAL) custom debug function
example: function(identifier) { return function(msg){... your debug function here ...} }
To Run Node Tests
Download yukon - https://github.com/jackspaniel/yukon/archive/master.zip
$ npm install
$ make test
To Do
- Stop populating res.locals and res.renderData with API response data. All API response data and errors should be tacked on to the req.nodules.callArgs[namespace] object. (Maybe rename callArgs to something a little less arg-y?) An app can add these convenience shortcuts if desired.
- Reconside stub behavior. Should all stubs move to apiSim behavior? What about brand new nodules where nothing is known about the API yet?
- Get demoApp working as standalone.
- Write more detailed unit tests?
- Hook up Travis CI and code coverage.
Features for future consideration
- Other forms of async data gathering. Currently yukon only knows how to make REST API calls. But it woudn't take much work to extend this behavior to any sort of asynchronous data store - such as a Mondo DB or Redis cache.
- Sequential API calls. Currently yukon makes all API calls in parallel. We've been fortunate in that we haven't needed dependent API calls yet.
- API error handling. It seems that there can be a huge variation in error behavior, and even in what constitutes an API error (status code-based?), from web-app to web-app. So for now I've punted on advanced API error handling, and let the app deal with it in the API callback. But if something like a standard is more or less agreed-upon, I will be happy to add flexible error handling.
Examples:
HTML response
(homePage.js from the demoApp)
module.exports = function(app) {
return {
route: ['/', '/home', '/special'],
apiCalls: [
{path: '/api/cms/home'},
{path: '/api/data/homeslices'}
],
preProcessor: function(req, res) {
this.debug('preProcessor called');
if (req.path.indexOf('special') > -1) {
this.apiCalls[1].params = {isSpecial: true};
this.templateName = 'altHomePage.jade';
}
},
postProcessor: function(req, res) {
this.debug('postProcessor called');
var clientMsg = res.locals.data2.specialMsg || res.locals.data2.msg;
res.renderData = {
globalNav: res.locals.globalNav,
cmsData: res.locals.data1,
myData: res.locals.data2,
clientMsg: clientMsg
};
}
};
};
JSON response
(getData.js from the demoApp)
module.exports = function(app) {
return {
route : '/json/getData/:id',
apiCalls: [
{path: '/api/getdata/'},
],
preProcessor: function(req, res) {
this.debug('preProcessor called');
this.apiCalls[0].params = {myParam: req.query.myParam};
},
postProcessor: function(req, res) {
this.debug('postProcessor called');
res.renderData = {
systemMsg: res.locals.data1.systemMsg,
data: res.locals.data1
};
}
};
};
Form submit
(submitForm.js from the demoApp)
var _ = require('lodash');
module.exports = function(app) {
return {
route : '/json/submitForm',
routeVerb: 'post',
apiCalls: [{
path: '/api/submitform',
verb: 'post',
bodyType: 'form',
}],
preProcessor: function(req, res) {
this.debug('preProcessor called');
if (!_.isEmpty(req.body)) {
this.apiCalls[0].bodyType = 'json';
this.apiCalls[0].params = req.body;
}
else {
this.apiCalls[0].params = req.query;
}
},
postProcessor: function(req, res) {
this.debug('postProcessor called');
res.renderData = {
response: res.locals.data1
};
}
};
};
App-defined middleware
(from demoApp.js)
function demoStart(req, res, next) {
debug("demoStart called");
res.locals.pretty = true;
if (req.nodule.contentType !== 'html' && req.path.indexOf('/json/') === 0)
req.nodule.contentType = 'json';
if (req.headers['user-agent'].match(/android/i))
req.deviceType = 'Android';
else if (req.headers['user-agent'].match(/iphone/i))
req.deviceType = 'iPhone';
else if (req.headers['user-agent'].match(/ipad/i))
req.deviceType = 'iPad';
else
req.deviceType = 'web';
next();
}
Global API callback and error handling
(from demoApp.js)
function demoApiCallback(callArgs, req, res, next) {
if (callArgs.apiError && !callArgs.handleError) {
debug(callArgs.apiError.stack || callArgs.apiError);
next(new Error('API failed for '+callArgs.path +': '+callArgs.apiError));
}
else {
var msg = "RESPONSE FROM "+callArgs.apiResponse.req.path+": statusCode=" + callArgs.apiResponse.statusCode;
debug(msg);
res.locals[callArgs.namespace].systemMsg = msg;
if (callArgs.apiResponse.req._headers)
res.locals[callArgs.namespace].customHeaders = callArgs.apiResponse.req._headers;
next();
}
}
For more examples see the Kitchen Sink and the rest of the Demo App
License
MIT