Socket
Socket
Sign inDemoInstall

yukon

Package Overview
Dependencies
Maintainers
1
Versions
43
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

yukon - npm Package Compare versions

Comparing version 1.2.0 to 1.2.1

10

package.json
{
"name": "yukon",
"version": "1.2.0",
"version": "1.2.1",
"description": "Self-discovering API-driven web components",

@@ -50,3 +50,9 @@ "main": "yukon.js",

"supertest": "^0.15.0"
}
},
"readme": "# yukon API framework\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n\nyukon is a component-based framework built on top of node/express - which makes 0-n asynchronous REST API calls in parallel to provide back-end data for each express request. It extends the [nodulejs component framework](https://github.com/jackspaniel/nodulejs). \n\nA really simple yukon component looks like this:\n```js\nmodule.exports = function(app) {\n return {\n \n route: '/home', \n \n templateName: 'homePage.jade',\n\n apiCalls: [\n {path: '/api/cms/home'},\n {path: '/api/data/homedata'}\n ],\n \n preProcessor: function(req, res) {\n // pre-API(s) business logic goes here\n },\n \n postProcessor: function(req, res) {\n // post-API(s) business logic goes here\n }\n };\n};\n```\n## Installation\n```\n$ npm install yukon\n```\n\n## Usage\n```\nrequire('yukon')(app, config); \n```\n+ __app__ = express instance.\n+ __config__ = any custom properties you want to add or defaults you want to override. See the [demoApp](https://github.com/jackspaniel/yukon/blob/master/demo/demoApp.js) for an example of a working yukon app. See the Config section below for more details. \n\n## What is a yukon nodule? \nA *__nodule__* is a self-discovering, self-registering web component tied to one or more express routes. With each incoming request, a nodule instance propagates throughout the express middleware chain as req.nodule. \n\nA *__yukon nodule__* extends the base nodule behavior to include REST API data gathering, stub-handling and template-rendering. Yukon attaches data returned from the API(s) as the res.yukon object, and sends res.yukon.renderData to the template or straight back to the client as JSON.\n\n*Nodulejs was split off from yukon to separate out the core self-discovery and initialization features, which can potentially be a building block for a wide variety of node applications or frameworks.*\n\nA nodule is analogous to a JSP or PHP page in those worlds. Unlike PHP/JSP behavior 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. 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.\n\n## Motivation \nFrom a __feature-development point of view__, we wanted to give developers the flexibility of [component-based architecture](http://en.wikipedia.org/wiki/Component-based_software_engineering) 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. \n\nOur feature devs spend 80-90% of their effort in jade templates or on the client side. For them, node components are often mostly a pass-through to our back-end 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.\n\nFrom 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.\n\nWe 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. \n\nThis diagram might make the concept a little more clear:\n\n![](http://i.imgur.com/eXExJi8.gif)\n\n## Config\n\nYukon config is broken into 3 sections:\n\n1. Nodule-specific properties\n2. API-specific properties\n3. App-defined middleware functions and global settings\n\n*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.*\n\n### Nodule-specific properties (config.noduleDefaults)\n\nYukon inherits the 4 core [nodulejs](https://github.com/jackspaniel/nodulejs) defaults:\n\n1. __route__: <span style=\"color:grey\">(REQUIRED)</span> one or more express routes - can be a string, RegExp, or array of either\n2. __routeVerb__: <span style=\"color:grey\">(OPTIONAL, default=get)</span> get, post, put, del\n3. __routeIndex__: <span style=\"color:grey\">(OPTIONAL, default=0)</span> use to match express routes before or after others, can be negative, like z-index\n4. __middlewares__: <span style=\"color:grey\">(OPTIONAL)</span> define this in your nodule to override the entire yukon request chain. See [404.js from the demoApp](https://github.com/jackspaniel/yukon/blob/master/demo/404.js) for example.\n\nYukon also adds the following optional nodule properties:\n\n1. __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.\n2. __templateExt:__ default template extension\n3. __contentType:__ 'html' and 'json' are the only current values\n4. __preProcessor:__ use this function to manipulate query params or other business logic before api call\n5. __postProcessor__: use this function to process data returned from the API before calling template or sending back to client as JSON\n6. __error:__ set to a string or an Error() instance to get the framework to call next(error)\n7. __apiCalls:__ array of API calls to made in parallel for this nodule, see the section below for details what constitutes an API call. \n<br>NOTE: global or semi-global calls like getProfile, getGlobalNav, etc. can be added to this array in the appPreApi middleware.\n\n### API-specific properties (config.apiDefaults)\n\nYukon defines the following properties for each API call. It is important to understand that these exist in a one-to-many relationship with nodules. \n\n1. __path:__ path to API (not including server). \n<br>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.\n2. __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).\n3. __verb:__ get, post, put, del\n4. __bodyType:__ valid values: json, form\n5. __host:__ path to the API server, can be set in app-defined middleware or overridden at the nodule level.\n6. __customHeaders:__ custom headers to sent with API call\n7. __timeout:__ (numeric) - max API return time in ms\n8. __useStub:__ set true to force framework to use stub instead of API\n9. __stubPath:__ can contain path or just name if in same folder\n<br>MAGIC ALERT: if not specified, app looks for [nodule name].stub.json in nodule folder\n\n### App-defined middlware\n\nAn app can create and use 4 optional express middleware functions, which splice in between the built-in yukon middleware (see [yukon.js](https://github.com/jackspaniel/yukon/blob/master/yukon.js) for more detail):\n\n1. __appStart:__ called at start of middleware, before nodule.preProcessor\n2. __appPreApi:__ called after nodule.preProcessor, before API call(s)\n3. __appPostApi:__ called after API call(s), before nodule.postProcessor\n4. __appFinish:__ called after nodule.postProcessor, before res.send() or res.\n\nAn 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.\n\n1. __apiCallBefore:__ a synchronous function executed before of every api call. Do any common API pre-processing here. \n2. __apiCallback:__ an asynchronous function executed after every api call, must execute next() if defined. Do error handling and other common post-API processing here. \n \n### Global properties\n\nThere are also 3 global config properties inherited from [nodulejs](https://github.com/jackspaniel/nodulejs):\n\n1. __dirs__: <span color=\"grey\">(OPTIONAL, default='/nodules')</span> *path(s) to look for your nodules, exclude property can be full or partal match* <br>__example:__ [{ path: '/app', exclude: ['demoApp.js', '.test.js', '/shared/'] }, { path: '/lib/nodules', exclude: ['.test.js'] }]\n2. __debugToConsole__: <span style=\"color:grey\">(OPTIONAL, default=false)</span> *set to true to see nodulejs debug output in the console* \n3. __customDebug__: <span style=\"color:grey\">(OPTIONAL)</span> *custom debug function* <br>__example:__ function(identifier) { return function(msg){... your debug function here ...} }\n\n### To Run Node Tests\n```\nDownload yukon - https://github.com/jackspaniel/yukon/archive/master.zip\n$ npm install\n$ make test \n```\n## To Do\n1. Reconsider stub behavior. Should all stubs move to apiSim behavior? What about brand new nodules where nothing is known about the API yet?\n2. Get demoApp working as standalone.\n3. Write more detailed unit tests?\n4. Hook up Travis CI and code coverage.\n\n## Features for future consideration\n+ __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 Mongo DB or Redis cache.\n+ __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.\n+ __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.\n\n## Examples:\n\n#### HTML response\n([homePage.js](https://github.com/jackspaniel/yukon/blob/master/demo/homePage/homePage.js) from the demoApp)\n```js\nmodule.exports = function(app) {\n return {\n \n route: ['/', '/home', '/special'], // multiple routes\n\n apiCalls: [\n {path: '/api/cms/home'},\n {path: '/api/data/homeslices'}\n ],\n \n // pre-API(s) business logic\n preProcessor: function(req, res) {\n this.debug('preProcessor called');\n\n if (req.path.indexOf('special') > -1) {\n this.apiCalls[1].params = {isSpecial: true}; // setting api params at request-time\n this.templateName = 'altHomePage.jade'; // using alternate template\n }\n },\n \n // post-API(s) business logic\n postProcessor: function(req, res) {\n this.debug('postProcessor called');\n\n var clientMsg = res.yukon.data2.specialMsg || res.yukon.data2.msg;\n\n res.yukon.renderData = {\n globalNav: res.yukon.globalNav,\n cmsData: res.yukon.data1,\n myData: res.yukon.data2,\n clientMsg: clientMsg\n };\n }\n };\n};\n```\n\n#### JSON response\n([getData.js](https://github.com/jackspaniel/yukon/blob/master/demo/json/getData.js) from the demoApp)\n```js\nmodule.exports = function(app) {\n return {\n \n route : '/json/getData/:id', \n\n apiCalls: [\n {path: '/api/getdata/'}, // :id is tacked on by the framework automatically\n ],\n\n preProcessor: function(req, res) {\n this.debug('preProcessor called');\n\n this.apiCalls[0].params = {myParam: req.query.myParam};\n },\n \n postProcessor: function(req, res) {\n this.debug('postProcessor called');\n\n res.yukon.renderData = {\n systemMsg: res.yukon.data1.systemMsg,\n data: res.yukon.data1\n };\n }\n };\n};\n```\n\n#### Form submit\n([submitForm.js](https://github.com/jackspaniel/yukon/blob/master/demo/json/submitForm.js) from the demoApp)\n```js\nvar _ = require('lodash');\n\nmodule.exports = function(app) {\n return {\n \n route : '/json/submitForm', \n\n routeVerb: 'post', // default = get \n \n apiCalls: [{\n path: '/api/submitform',\n verb: 'post', // post to API\n bodyType: 'form', // default = 'json'\n }],\n\n preProcessor: function(req, res) {\n this.debug('preProcessor called');\n \n if (!_.isEmpty(req.body)) {\n this.apiCalls[0].bodyType = 'json';\n this.apiCalls[0].params = req.body; // JSON body\n }\n else {\n this.apiCalls[0].params = req.query; // url-encoded\n }\n },\n\n postProcessor: function(req, res) {\n this.debug('postProcessor called');\n\n res.yukon.renderData = {\n response: res.yukon.data1\n };\n }\n };\n};\n```\n\n#### App-defined middleware\n(from [demoApp.js](https://github.com/jackspaniel/yukon/blob/master/demo/demoApp.js))\n```js\nfunction demoStart(req, res, next) {\n debug(\"demoStart called\");\n\n res.locals.pretty = true; // jade pretty setting - turn off at the component level if necessary\n\n // example of setting nodule property globally\n if (req.nodule.contentType !== 'html' && req.path.indexOf('/json/') === 0)\n req.nodule.contentType = 'json'; \n\n // example of app-level logic - simple device detection (used throughout demoApp)\n if (req.headers['user-agent'].match(/android/i))\n req.deviceType = 'Android';\n else if (req.headers['user-agent'].match(/iphone/i))\n req.deviceType = 'iPhone';\n else if (req.headers['user-agent'].match(/ipad/i))\n req.deviceType = 'iPad';\n else \n req.deviceType = 'web';\n\n next();\n}\n```\n\n#### Global API callback and error handling\n(from [demoApp.js](https://github.com/jackspaniel/yukon/blob/master/demo/demoApp.js))\n```js\nfunction demoApiCallback(callArgs, req, res, next) {\n \n // custom error handling\n if (callArgs.apiError && !callArgs.handleError) {\n debug(callArgs.apiError.stack || callArgs.apiError);\n next(new Error('API failed for '+callArgs.path +': '+callArgs.apiError));\n }\n else {\n var msg = \"RESPONSE FROM \"+callArgs.apiResponse.req.path+\": statusCode=\" + callArgs.apiResponse.statusCode;\n debug(msg); \n \n // example of app-level logic on every api response (remember there can be multiple API calls per request)\n res.yukon[callArgs.namespace].systemMsg = msg;\n\n // used by kitchen sink to test if API custom headers are being set\n if (callArgs.apiResponse.req._headers)\n res.yukon[callArgs.namespace].customHeaders = callArgs.apiResponse.req._headers; \n\n next();\n }\n}\n```\n\nFor more examples see the [Kitchen Sink](https://github.com/jackspaniel/yukon/blob/master/demo/kitchenSink/kitchenSink.js) and the rest of the [Demo App](https://github.com/jackspaniel/yukon/blob/master/demo/)\n\n## License\n### MIT\n\n[npm-image]: https://img.shields.io/npm/v/yukon.svg?style=flat\n[npm-url]: https://www.npmjs.com/package/yukon\n[downloads-image]: https://img.shields.io/npm/dm/yukon.svg?style=flat\n[downloads-url]: https://npmjs.org/package/yukon\n",
"readmeFilename": "README.md",
"gitHead": "2512d9961e47abcb9e3d706adeab29b1920f057a",
"_id": "yukon@1.2.0",
"_shasum": "bad087d20535273d588c433992ee3cdd60e4974c",
"_from": "yukon@^1.2.0"
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc