├── .editorconfig ├── .gitignore ├── .travis.yml ├── example ├── error-management │ ├── error-handler.js │ ├── index.js │ ├── package.json │ └── readme.md ├── function_mw │ ├── index.js │ ├── package.json │ └── readme.md └── helloworld │ ├── index.js │ ├── package.json │ └── readme.md ├── index.js ├── license ├── package.json ├── readme.md └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | indent_style = tab 7 | trim_trailing_whitespace = true 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #### joe made this: http://goel.io/joe 2 | 3 | #####=== SublimeText ===##### 4 | # cache files for sublime text 5 | *.tmlanguage.cache 6 | *.tmPreferences.cache 7 | *.stTheme.cache 8 | 9 | # workspace files are user-specific 10 | *.sublime-workspace 11 | 12 | # project files should be checked into the repository, unless a significant 13 | # proportion of contributors will probably not be using SublimeText 14 | # *.sublime-project 15 | 16 | # sftp configuration file 17 | sftp-config.json 18 | 19 | #####=== Node ===##### 20 | 21 | # Logs 22 | logs 23 | *.log 24 | 25 | # Runtime data 26 | pids 27 | *.pid 28 | *.seed 29 | 30 | # Directory for instrumented libs generated by jscoverage/JSCover 31 | lib-cov 32 | 33 | # Coverage directory used by tools like istanbul 34 | coverage 35 | 36 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 37 | .grunt 38 | 39 | # node-waf configuration 40 | .lock-wscript 41 | 42 | # Compiled binary addons (http://nodejs.org/api/addons.html) 43 | build/Release 44 | 45 | # Dependency directory 46 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- 47 | node_modules 48 | 49 | # Debug log from npm 50 | npm-debug.log 51 | 52 | yarn.lock 53 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 4 4 | - 'stable' 5 | sudo: false 6 | -------------------------------------------------------------------------------- /example/error-management/error-handler.js: -------------------------------------------------------------------------------- 1 | const CoMws = require('comws'); 2 | 3 | const mws = new CoMws(); 4 | 5 | // eslint-disable-next-line require-yield, no-unused-vars 6 | mws.use(function * (next) { 7 | throw new Error('Yike!'); 8 | }); 9 | 10 | // eslint-disable-next-line require-yield, no-unused-vars 11 | mws.use(function * (ctx, err, next) { 12 | process.stderr.write(err.message); 13 | }); 14 | 15 | mws.run(); 16 | -------------------------------------------------------------------------------- /example/error-management/index.js: -------------------------------------------------------------------------------- 1 | const CoMws = require('comws'); 2 | 3 | const mws = new CoMws(); 4 | 5 | // eslint-disable-next-line require-yield, no-unused-vars 6 | mws.use(function * (next) { 7 | throw new Error('Yike!'); 8 | }); 9 | 10 | mws.run(); 11 | -------------------------------------------------------------------------------- /example/error-management/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "helloworld", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"no test exists\" && exit 0" 8 | }, 9 | "author": "", 10 | "license": "MIT", 11 | "dependencies": { 12 | "comws": "^1.0.0" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /example/error-management/readme.md: -------------------------------------------------------------------------------- 1 | # hello world example 2 | 3 | this example explain you error management with co-mws 4 | 5 | ##How to run this example 6 | 7 | cwd here, then to run with iojs: 8 | 9 | ```sh 10 | npm install 11 | node . 12 | ``` 13 | 14 | If you are using node 0.11 or 0.12, remember to add `harmony` flag: 15 | 16 | ```sh 17 | npm install 18 | node --harmony . 19 | ``` 20 | 21 | If it work, you should see on console a pretty formatted error message: 22 | 23 | ``` 24 | Error: Yike! 25 | 26 | - index.js:5 27 | co-mws/example/error-management/i 28 | ndex.js:5:11 29 | 30 | - GeneratorFunctionPrototype.next 31 | 32 | - index.js:61 onFulfilled 33 | [co-mws]/[co]/index.js:61:19 34 | 35 | - index.js:50 36 | [co-mws]/[co]/index.js:50:5 37 | 38 | - index.js:49 co 39 | [co-mws]/[co]/index.js:49:10 40 | 41 | - index.js:30 createPromise 42 | [co-mws]/[co]/index.js:30:15 43 | 44 | - index.js:89 step 45 | co-mws/dist/index.js:89:45 46 | 47 | - index.js:104 CoMws.run 48 | co-mws/dist/index.js:104:24 49 | 50 | - index.js:11 Object. 51 | co-mws/example/error-management/i 52 | ndex.js:11:5 53 | 54 | - module.js:444 Module._compile 55 | module.js:444:26 56 | 57 | ``` 58 | 59 | 60 | 61 | 62 | ##Custom error handler 63 | 64 | It's also possible to install a custom error handler. 65 | Error handlers are middleware with a signature of function(ctx, err, next). 66 | When a middleware throws, comws search for middlewares with this signature 67 | that follows in chain the one that throws. If no one is found, a default one 68 | get called (and print what you see in previous example) 69 | 70 | Run this example: 71 | 72 | cwd here, then to run with iojs: 73 | 74 | ```sh 75 | npm install 76 | node error-handler 77 | ``` 78 | 79 | If you are using node 0.11 or 0.12, remember to add `harmony` flag: 80 | 81 | ```sh 82 | npm install 83 | node --harmony error-handler 84 | ``` 85 | 86 | If it work, you should see on console: 87 | 88 | ``` 89 | Yike! 90 | ``` 91 | -------------------------------------------------------------------------------- /example/function_mw/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const CoMws = require('comws'); 4 | 5 | const mws = new CoMws(); 6 | 7 | // eslint-disable-next-line require-yield, no-unused-vars 8 | mws.use(function (next) { 9 | const _this = this; 10 | 11 | _this.result += '\n first at ' + new Date().getTime(); 12 | return next().then(function () { 13 | _this.result += '\n after second at ' + new Date().getTime(); 14 | }); 15 | }); 16 | 17 | // eslint-disable-next-line require-yield, no-unused-vars 18 | mws.use(function * (next) { 19 | this.result += '\n second running at ' + new Date().getTime(); 20 | 21 | return new Promise(function (resolve) { 22 | setTimeout(resolve, 1000); 23 | }); 24 | }); 25 | 26 | const ctx = {result: 'start at ' + new Date().getTime()}; 27 | 28 | mws.run(ctx).then(function () { 29 | process.stderr.write(ctx.result); 30 | }); 31 | -------------------------------------------------------------------------------- /example/function_mw/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "helloworld", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"no test exists\" && exit 0" 8 | }, 9 | "author": "", 10 | "license": "MIT", 11 | "dependencies": { 12 | "comws": "^1.0.0" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /example/function_mw/readme.md: -------------------------------------------------------------------------------- 1 | # hello world example 2 | 3 | This example show you how to define a function middleware (one that don't use generators). 4 | 5 | Please note that if you return a promise, execution of downstream middlewares 6 | continue only when the promise is resolved. 7 | 8 | If you don't need this async pattern, simply return a value. Comws will take care of 9 | wrap it with a Promise.resolve, so downstream middlewares are not to be aware you're 10 | returning a non promise. 11 | 12 | ##run this example 13 | 14 | cwd here, then, to run with iojs 15 | 16 | ```sh 17 | npm install 18 | node . 19 | ``` 20 | 21 | If you are using node 0.11 or 0.12, remember to add `harmony` flag 22 | 23 | ```sh 24 | npm install 25 | node --harmony . 26 | ``` 27 | 28 | If it work, you should see on console 29 | 30 | ``` 31 | start at 1426099977350 32 | first at 1426099977352 33 | second running at 1426099977353 34 | after second at 1426099978357 35 | 36 | ``` 37 | -------------------------------------------------------------------------------- /example/helloworld/index.js: -------------------------------------------------------------------------------- 1 | const CoMws = require('comws'); 2 | 3 | const mws = new CoMws(); 4 | 5 | mws.use(function * (next) { 6 | this.result += ' hello'; 7 | yield next(); 8 | }); 9 | 10 | mws.use(function * (next) { 11 | this.result += ' world'; 12 | yield next(); 13 | }); 14 | 15 | const ctx = {result: 'yet another'}; 16 | 17 | mws.run(ctx).then(function () { 18 | process.stdout.write(ctx.result); 19 | }); 20 | -------------------------------------------------------------------------------- /example/helloworld/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "helloworld", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"no test exists\" && exit 0" 8 | }, 9 | "author": "", 10 | "license": "MIT", 11 | "dependencies": { 12 | "comws": "^1.0.0" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /example/helloworld/readme.md: -------------------------------------------------------------------------------- 1 | # hello world example 2 | 3 | a simple example in es5, the same one you saw in readme 4 | 5 | ##run this example 6 | 7 | cwd here, then, to run with iojs 8 | 9 | ```sh 10 | npm install 11 | node . 12 | ``` 13 | 14 | If you are using node 0.11 or 0.12, remember to add `harmony` flag 15 | 16 | ```sh 17 | npm install 18 | node --harmony . 19 | ``` 20 | 21 | If it work, you should see on console `yet another hello world` 22 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const co = require('co'); 4 | const isPromise = require('is-promise'); 5 | const PrettyError = require('pretty-error'); 6 | 7 | const pe = new PrettyError(); 8 | const debug = require('debug')('comws'); 9 | 10 | function isGenerator(fn) { 11 | return fn.constructor.name.endsWith('GeneratorFunction'); 12 | } 13 | 14 | module.exports = class CoMws { 15 | constructor() { 16 | this.mws = []; 17 | } 18 | 19 | use(mw) { 20 | if (arguments.length === 1) { 21 | this.mws.push(mw); 22 | } else { 23 | this.mws.push.apply(this.mws, Array.from(arguments)); 24 | } 25 | return this; 26 | } 27 | 28 | handleError(ctx, err, mwIdx) { 29 | let idxErrMiddleware = mwIdx + 1; 30 | 31 | while (idxErrMiddleware < this.mws.length) { 32 | const errMiddleware = this.mws[idxErrMiddleware]; 33 | 34 | if (errMiddleware.length === 3) { 35 | const runner = co.wrap(errMiddleware); 36 | return runner(ctx, err, () => {}); 37 | } 38 | 39 | idxErrMiddleware++; 40 | } 41 | 42 | const renderedError = pe.render(err); 43 | 44 | process.stderr.write(renderedError.stack + '\n'); 45 | return err; 46 | } 47 | 48 | run(ctx) { 49 | const step = idx => { 50 | if (idx === this.mws.length) { 51 | return Promise.resolve(true); 52 | } 53 | 54 | const currentMw = this.mws[idx]; 55 | 56 | const next = err => { 57 | if (err) { 58 | return this.handleError(ctx, err, idx); 59 | } 60 | 61 | const result = step(idx + 1); 62 | 63 | if (isPromise(result)) { 64 | return result; 65 | } 66 | 67 | return result instanceof Error ? 68 | Promise.reject(result) : 69 | Promise.resolve(result); 70 | }; 71 | 72 | const runner = isGenerator(currentMw) ? 73 | co.wrap(currentMw) : 74 | currentMw; 75 | 76 | debug(`running ${currentMw.name || 'anonymous middleware'} idetified as ${isGenerator(currentMw) ? 'generator' : 'normal function'}`); 77 | 78 | let result; 79 | 80 | try { 81 | debug(`running ${currentMw.name || 'anonymous middleware'} with context`); 82 | 83 | if (runner.length === 2) { 84 | debug(`running ${currentMw.name || 'anonymous middleware'} with context as argument`); 85 | result = runner(ctx, next); 86 | } else { 87 | debug(`running ${currentMw.name || 'anonymous middleware'} with context binded to this`); 88 | result = runner.call(ctx, next); 89 | } 90 | } catch (err) { 91 | debug(`${currentMw.name || 'anonymous middleware'} throws ${err}`); 92 | 93 | return next(err); 94 | } 95 | 96 | if (isPromise(result)) { 97 | return result 98 | .then(res => { 99 | debug(`${currentMw.name || 'anonymous middleware'} resolved to ${res}`); 100 | 101 | return res; 102 | }) 103 | .catch(err => { 104 | debug(`${currentMw.name || 'anonymous middleware'} rejected with ${err}`); 105 | 106 | return next(err); 107 | }); 108 | } 109 | 110 | debug(`${currentMw.name || 'anonymous middleware'} return ${result}`); 111 | 112 | return Promise.resolve(result); 113 | }; 114 | 115 | return step(0); 116 | } 117 | }; 118 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | Copyright (c) 2016 Andrea Parodi 3 | 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "comws", 3 | "version": "2.1.0", 4 | "description": "Expressive middleware for node.js", 5 | "scripts": { 6 | "test": "ava && xo index.js test.js" 7 | }, 8 | "engines": { 9 | "node": ">=4" 10 | }, 11 | "repository": "parro-it/comws", 12 | "keywords": [ 13 | "co", 14 | "middlewares", 15 | "koa", 16 | "middleware", 17 | "mw", 18 | "mws" 19 | ], 20 | "devDependencies": { 21 | "ava": "^0.24.0", 22 | "xo": "^0.18.1" 23 | }, 24 | "dependencies": { 25 | "co": "^4.0.0", 26 | "debug": "^3.1.0", 27 | "is-promise": "^2.0.0", 28 | "pretty-error": "^2.0.3" 29 | }, 30 | "author": "andrea@parro.it", 31 | "license": "MIT", 32 | "files": [ 33 | "index.js" 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # comws 2 | 3 | [![Greenkeeper badge](https://badges.greenkeeper.io/parro-it/comws.svg)](https://greenkeeper.io/) 4 | 5 | > Expressive middleware for node.js using generators via [co](https://github.com/visionmedia/co) to make node applications more enjoyable to write. Comws middleware flow in a stack-like manner exactly like koa ones. Use of generators also greatly increases the readability and robustness of your application. 6 | 7 | [![Travis Build Status](https://img.shields.io/travis/parro-it/comws.svg)](http://travis-ci.org/parro-it/comws) 8 | [![NPM module](https://img.shields.io/npm/v/comws.svg)](https://npmjs.org/package/comws) 9 | [![NPM downloads](https://img.shields.io/npm/dt/comws.svg)](https://npmjs.org/package/comws) 10 | 11 | # Installation 12 | 13 | ```bash 14 | npm install comws --save 15 | ``` 16 | 17 | Comws is supported in all versions of node > 4. 18 | 19 | # Getting started 20 | 21 | See all examples in example folder to get started. 22 | 23 | Open an issue if you have any question or suggestion. 24 | 25 | # Example 26 | 27 | ```js 28 | const CoMws = require('comws'); 29 | const mws = new CoMws(); 30 | 31 | mws.use(function *(next){ 32 | this.result += ' hello'; 33 | yield next(); 34 | }); 35 | 36 | mws.use(function *(next){ 37 | this.result += ' world'; 38 | yield next(); 39 | }); 40 | 41 | const ctx = {result: 'yet another'}; 42 | 43 | mws.run(ctx).then(function() { 44 | //ctx.result === 'yet another hello world' 45 | }); 46 | 47 | ``` 48 | 49 | # Use multiple middlewares 50 | 51 | Starting from version 2.1, you can also 52 | use multiple middleware in the same `use` call: 53 | 54 | ```js 55 | const CoMws = require('comws'); 56 | const {mw1, mw2} = require('middlewares'); 57 | 58 | const mws = new CoMws(); 59 | 60 | mws.use(mw1, mw2); 61 | ``` 62 | 63 | or also chain `use` calls: 64 | 65 | ```js 66 | const CoMws = require('comws'); 67 | const {mw1, mw2} = require('middlewares'); 68 | 69 | const mws = new CoMws(); 70 | 71 | mws.use(mw1).use(mw2); 72 | ``` 73 | 74 | # Running tests 75 | 76 | ``` 77 | $ npm install && npm test 78 | ``` 79 | 80 | 81 | # License 82 | 83 | The MIT License (MIT) 84 | 85 | Copyright (c) 2016 parro-it 86 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import co from 'co'; 2 | import test from 'ava'; 3 | import CoMws from '.'; 4 | 5 | const setupMws = co.wrap(function * () { 6 | const mws = new CoMws(); 7 | const ctx = {result: 'yet another'}; 8 | 9 | mws.use(function * (next) { 10 | this.result += yield Promise.resolve(' hello'); 11 | yield next(); 12 | }); 13 | 14 | mws.use(function * (next) { 15 | this.result += yield Promise.resolve(' world'); 16 | yield next(); 17 | }); 18 | 19 | yield mws.run(ctx); 20 | 21 | return {mws, ctx}; 22 | }); 23 | 24 | const setupErrorMws = co.wrap(function * () { 25 | const mws = new CoMws(); 26 | mws.use(function * (next) { 27 | this.result = ('hello'); 28 | yield next(); 29 | }); 30 | 31 | // eslint-disable-next-line require-yield 32 | mws.use(function * () { 33 | throw new Error('test-error'); 34 | }); 35 | 36 | // eslint-disable-next-line require-yield, no-unused-vars 37 | mws.use(function * (ctx, err, next) { 38 | ctx.ex = err; 39 | }); 40 | 41 | const ctx = {}; 42 | 43 | yield mws.run(ctx); 44 | 45 | return {mws, ctx}; 46 | }); 47 | 48 | test('register all mws', async t => { 49 | const ctx = await setupMws(); 50 | t.is(ctx.mws.mws.length, 2); 51 | }); 52 | 53 | test('can construct instance', async t => { 54 | const ctx = await setupMws(); 55 | t.is(typeof ctx.mws, 'object'); 56 | }); 57 | 58 | test('execute all mws', async t => { 59 | const ctx = await setupMws(); 60 | t.is(ctx.ctx.result, 'yet another hello world'); 61 | }); 62 | 63 | test('handle errors', async t => { 64 | const ctx = await setupErrorMws(); 65 | t.is(ctx.ctx.ex.message, 'test-error'); 66 | }); 67 | 68 | test('allow function mw returning next', async t => { 69 | const ctx = {}; 70 | const mws = new CoMws(); 71 | 72 | mws.use(function (next) { 73 | this.result = 'hello'; 74 | return next(); 75 | }); 76 | 77 | // eslint-disable-next-line require-yield 78 | mws.use(function * (next) { 79 | this.result += ' world'; 80 | next(); 81 | }); 82 | 83 | await mws.run(ctx); 84 | 85 | t.is(ctx.result, 'hello world'); 86 | }); 87 | 88 | test('allow function mw returning a promise', async t => { 89 | const ctx = {}; 90 | 91 | const mws = new CoMws(); 92 | 93 | mws.use(function (next) { 94 | return new Promise(resolve => { 95 | next().then(() => { 96 | this.result += ' world'; 97 | resolve(); 98 | }); 99 | }); 100 | }); 101 | 102 | // eslint-disable-next-line require-yield 103 | mws.use(function * (next) { 104 | this.result = 'hello'; 105 | next(); 106 | }); 107 | 108 | await mws.run(ctx); 109 | t.is(ctx.result, 'hello world'); 110 | }); 111 | 112 | test('allow function mw returning a normal value', async t => { 113 | const ctx = {}; 114 | const mws = new CoMws(); 115 | 116 | mws.use(function * (next) { 117 | this.result = yield Promise.resolve('hello'); 118 | yield next(); 119 | }); 120 | 121 | // eslint-disable-next-line require-yield, no-unused-vars 122 | mws.use(function (next) { 123 | this.result += ' world'; 124 | return null; 125 | }); 126 | 127 | await mws.run(ctx); 128 | t.is(ctx.result, 'hello world'); 129 | }); 130 | 131 | test('allow generators, arrow and normal function with ctx arg', async t => { 132 | const ctx = {}; 133 | const mws = new CoMws(); 134 | 135 | mws.use((c, next) => { 136 | c.result = 'hello'; 137 | return next(); 138 | }); 139 | 140 | mws.use((c, next) => { 141 | c.result += ' magic'; 142 | return next(); 143 | }); 144 | 145 | mws.use((c, next) => { 146 | c.result += ' world'; 147 | next(); 148 | }); 149 | 150 | await mws.run(ctx); 151 | t.is(ctx.result, 'hello magic world'); 152 | }); 153 | --------------------------------------------------------------------------------