├── .gitignore ├── tslint.json ├── SECURITY.md ├── .editorconfig ├── .travis.yml ├── tsconfig.json ├── LICENSE ├── package.json ├── README.md └── src ├── index.ts └── index.spec.ts /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | coverage/ 3 | node_modules/ 4 | npm-debug.log 5 | dist/ 6 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["tslint-config-standard", "tslint-config-prettier"] 3 | } 4 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Security contact information 4 | 5 | To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. 6 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: http://EditorConfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_size = 2 7 | indent_style = space 8 | end_of_line = lf 9 | charset = utf-8 10 | trim_trailing_whitespace = true 11 | insert_final_newline = true 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | 4 | notifications: 5 | email: 6 | on_success: never 7 | on_failure: change 8 | 9 | node_js: 10 | - '8' 11 | - 'stable' 12 | 13 | after_script: "npm install coveralls@2 && cat ./coverage/lcov.info | coveralls" 14 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2015", 4 | "lib": ["es2015"], 5 | "rootDir": "src", 6 | "outDir": "dist", 7 | "module": "commonjs", 8 | "strict": true, 9 | "declaration": true, 10 | "sourceMap": true, 11 | "inlineSources": true 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Blake Embrey (hello@blakeembrey.com) 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 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "throwback", 3 | "version": "4.1.0", 4 | "description": "Simple asynchronous middleware pattern", 5 | "main": "dist/index.js", 6 | "typings": "dist/index.d.ts", 7 | "files": [ 8 | "dist/" 9 | ], 10 | "scripts": { 11 | "prettier": "prettier --write", 12 | "lint": "tslint \"src/**/*.ts\" --project tsconfig.json", 13 | "format": "npm run prettier -- README.md \"src/**/*.{js,ts}\"", 14 | "build": "rimraf dist && tsc", 15 | "specs": "jest --coverage", 16 | "test": "npm run -s lint && npm run -s build && npm run -s specs && npm run -s size", 17 | "prepare": "npm run build", 18 | "size": "size-limit" 19 | }, 20 | "repository": { 21 | "type": "git", 22 | "url": "git://github.com/serviejs/throwback.git" 23 | }, 24 | "keywords": [ 25 | "middleware", 26 | "async", 27 | "compose", 28 | "promise", 29 | "ware", 30 | "layer" 31 | ], 32 | "author": { 33 | "name": "Blake Embrey", 34 | "email": "hello@blakeembrey.com", 35 | "url": "http://blakeembrey.me" 36 | }, 37 | "license": "MIT", 38 | "bugs": { 39 | "url": "https://github.com/serviejs/throwback/issues" 40 | }, 41 | "homepage": "https://github.com/serviejs/throwback", 42 | "size-limit": [ 43 | { 44 | "path": "./dist/index.js", 45 | "limit": "90 B" 46 | } 47 | ], 48 | "jest": { 49 | "roots": [ 50 | "/src/" 51 | ], 52 | "transform": { 53 | "\\.tsx?$": "ts-jest" 54 | }, 55 | "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$", 56 | "moduleFileExtensions": [ 57 | "ts", 58 | "tsx", 59 | "js", 60 | "jsx", 61 | "json", 62 | "node" 63 | ] 64 | }, 65 | "husky": { 66 | "hooks": { 67 | "pre-commit": "lint-staged" 68 | } 69 | }, 70 | "lint-staged": { 71 | "*.{js,json,css,md}": [ 72 | "npm run prettier", 73 | "git add" 74 | ] 75 | }, 76 | "publishConfig": { 77 | "access": "public" 78 | }, 79 | "devDependencies": { 80 | "@types/jest": "^24.0.13", 81 | "@types/node": "^12.0.7", 82 | "husky": "^2.4.0", 83 | "jest": "^24.8.0", 84 | "lint-staged": "^8.2.0", 85 | "prettier": "^1.18.2", 86 | "rimraf": "^2.6.2", 87 | "size-limit": "^1.3.6", 88 | "ts-jest": "^24.0.2", 89 | "tslint": "^5.10.0", 90 | "tslint-config-prettier": "^1.18.0", 91 | "tslint-config-standard": "^8.0.1", 92 | "typescript": "^3.0.3" 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Throwback 2 | 3 | [![NPM version](https://img.shields.io/npm/v/throwback.svg?style=flat)](https://npmjs.org/package/throwback) 4 | [![NPM downloads](https://img.shields.io/npm/dm/throwback.svg?style=flat)](https://npmjs.org/package/throwback) 5 | [![Build status](https://img.shields.io/travis/serviejs/throwback.svg?style=flat)](https://travis-ci.org/serviejs/throwback) 6 | [![Test coverage](https://img.shields.io/coveralls/serviejs/throwback.svg?style=flat)](https://coveralls.io/r/serviejs/throwback?branch=master) 7 | 8 | > Simple asynchronous middleware pattern. 9 | 10 | ## Installation 11 | 12 | ``` 13 | npm install throwback --save 14 | ``` 15 | 16 | ## Usage 17 | 18 | Compose asynchronous (promise-returning) functions. 19 | 20 | ```js 21 | const { compose } = require("throwback"); 22 | 23 | const fn = compose([ 24 | async function(ctx, next) { 25 | console.log(1); 26 | 27 | try { 28 | await next(); 29 | } catch (err) { 30 | console.log("throwback", err); 31 | } 32 | 33 | console.log(4); 34 | }, 35 | async function(ctx, next) { 36 | console.log(2); 37 | 38 | return next(); 39 | } 40 | ]); 41 | 42 | // Callback runs at the end of the stack, before 43 | // the middleware bubbles back to the beginning. 44 | fn({}, function(ctx) { 45 | console.log(3); 46 | 47 | ctx.status = 404; 48 | }); 49 | ``` 50 | 51 | **Tip:** In development (`NODE_ENV !== "production"`), `compose` will throw errors when you do something unexpected. In production, the faster non-error code paths are used. 52 | 53 | ### Example 54 | 55 | Build a micro HTTP server! 56 | 57 | ```js 58 | const { createServer } = require("http"); 59 | const finalhandler = require("finalhandler"); // Example only, not compatible with single `ctx` arg. 60 | const { compose } = require("throwback"); 61 | 62 | const app = compose([ 63 | function({ req, res }, next) { 64 | res.end("Hello world!"); 65 | } 66 | ]); 67 | 68 | createServer(function(req, res) { 69 | return app({ req, res }, finalhandler()); 70 | }).listen(3000); 71 | ``` 72 | 73 | ## Use Cases 74 | 75 | - HTTP requests (e.g. [`popsicle`](https://github.com/serviejs/popsicle)) 76 | - HTTP servers (e.g. [`servie`](https://github.com/serviejs/servie)) 77 | - Processing pipelines (e.g. [`scrappy`](https://github.com/blakeembrey/node-scrappy)) 78 | 79 | ## Inspiration 80 | 81 | Built for [`servie`](https://github.com/serviejs) and inspired by [`koa-compose`](https://github.com/koajs/compose). 82 | 83 | ## License 84 | 85 | MIT 86 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Next function supports optional `ctx` replacement for following middleware. 3 | */ 4 | export type Next = () => Promise; 5 | 6 | /** 7 | * Middleware function pattern. 8 | */ 9 | export type Middleware = (ctx: T, next: Next) => U | Promise; 10 | 11 | /** 12 | * Final function has no `next()`. 13 | */ 14 | export type Done = (ctx: T) => U | Promise; 15 | 16 | /** 17 | * Composed function signature. 18 | */ 19 | export type Composed = (ctx: T, done: Done) => Promise; 20 | 21 | /** 22 | * Debug mode wrapper for middleware functions. 23 | */ 24 | function debugMiddleware( 25 | middleware: Array> 26 | ): Composed { 27 | if (!Array.isArray(middleware)) { 28 | throw new TypeError( 29 | `Expected middleware to be an array, got ${typeof middleware}` 30 | ); 31 | } 32 | 33 | for (const fn of middleware) { 34 | if ((typeof fn as any) !== "function") { 35 | // tslint:disable-line 36 | throw new TypeError( 37 | `Expected middleware to contain functions, but got ${typeof fn}` 38 | ); 39 | } 40 | } 41 | 42 | return function composedDebug(ctx: T, done: Done) { 43 | if ((typeof done as any) !== "function") { 44 | // tslint:disable-line 45 | throw new TypeError( 46 | `Expected the last argument to be \`done(ctx)\`, but got ${typeof done}` 47 | ); 48 | } 49 | 50 | let index = 0; 51 | 52 | function dispatch(pos: number): Promise { 53 | const fn = middleware[pos] || done; 54 | 55 | index = pos; 56 | 57 | return new Promise(resolve => { 58 | const result = fn(ctx, function next() { 59 | if (pos < index) { 60 | throw new TypeError("`next()` called multiple times"); 61 | } 62 | 63 | if (pos > middleware.length) { 64 | throw new TypeError( 65 | "Composed `done(ctx)` function should not call `next()`" 66 | ); 67 | } 68 | 69 | return dispatch(pos + 1); 70 | }); 71 | 72 | if ((result as any) === undefined) { 73 | // tslint:disable-line 74 | throw new TypeError( 75 | "Expected middleware to return `next()` or a value" 76 | ); 77 | } 78 | 79 | return resolve(result); 80 | }); 81 | } 82 | 83 | return dispatch(index); 84 | }; 85 | } 86 | 87 | /** 88 | * Production-mode middleware composition (no errors thrown). 89 | */ 90 | function composeMiddleware( 91 | middleware: Array> 92 | ): Composed { 93 | function dispatch(pos: number, ctx: T, done: Done): Promise { 94 | const fn = middleware[pos] || done; 95 | 96 | return new Promise(resolve => { 97 | return resolve( 98 | fn(ctx, function next() { 99 | return dispatch(pos + 1, ctx, done); 100 | }) 101 | ); 102 | }); 103 | } 104 | 105 | return function composed(ctx, done) { 106 | return dispatch(0, ctx, done); 107 | }; 108 | } 109 | 110 | /** 111 | * Compose an array of middleware functions into a single function. 112 | */ 113 | export const compose = 114 | process.env.NODE_ENV === "production" ? composeMiddleware : debugMiddleware; 115 | -------------------------------------------------------------------------------- /src/index.spec.ts: -------------------------------------------------------------------------------- 1 | import { compose, Next } from "./index"; 2 | 3 | describe("throwback", () => { 4 | // Run tests on each code path. 5 | runTests("production"); 6 | runTests("development"); 7 | 8 | describe("debug mode", () => { 9 | it("should select debug mode based on node env by default", () => { 10 | const fn = compose([]); 11 | 12 | expect(fn.name).toEqual("composedDebug"); 13 | }); 14 | }); 15 | 16 | describe("debug errors", () => { 17 | it("throw when input is not an array", () => { 18 | expect(() => (compose as any)("test", true)).toThrow( 19 | "Expected middleware to be an array, got string" 20 | ); 21 | }); 22 | 23 | it("throw when values are not functions", () => { 24 | expect(() => (compose as any)([1, 2, 3], true)).toThrow( 25 | "Expected middleware to contain functions, but got number" 26 | ); 27 | }); 28 | 29 | it("throw when done is not a function", () => { 30 | const fn = compose([]); 31 | 32 | expect(() => (fn as any)(true)).toThrow( 33 | "Expected the last argument to be `done(ctx)`, but got undefined" 34 | ); 35 | }); 36 | 37 | it("throw when calling `next()` multiple times", async () => { 38 | const fn = compose([ 39 | function(value: any, next: Next) { 40 | return next().then(() => next()); 41 | } 42 | ]); 43 | 44 | await expect(fn({}, () => Promise.resolve())).rejects.toEqual( 45 | new Error("`next()` called multiple times") 46 | ); 47 | }); 48 | 49 | it("should throw if final function attempts to call `next()`", async () => { 50 | const fn = compose([]); 51 | 52 | await expect( 53 | fn({}, ((ctx: any, next: any) => next()) as any) 54 | ).rejects.toEqual( 55 | new TypeError("Composed `done(ctx)` function should not call `next()`") 56 | ); 57 | }); 58 | 59 | it("should throw if function returns `undefined`", async () => { 60 | const fn = compose([ 61 | function(ctx) { 62 | /* Ignore. */ 63 | } 64 | ]); 65 | 66 | await expect(fn(true, () => Promise.resolve())).rejects.toEqual( 67 | new TypeError("Expected middleware to return `next()` or a value") 68 | ); 69 | }); 70 | }); 71 | }); 72 | 73 | /** 74 | * Execute tests in each "mode". 75 | */ 76 | function runTests(nodeEnv: string) { 77 | jest.resetModules() 78 | 79 | process.env.NODE_ENV = nodeEnv; 80 | 81 | const { compose } = require('./index'); 82 | 83 | describe(`compose middleware with env ${nodeEnv}`, () => { 84 | it("should select debug mode based on node env by default", () => { 85 | const fn = compose([]); 86 | const expectedName = 87 | nodeEnv === "production" ? "composed" : "composedDebug"; 88 | 89 | expect(fn.name).toEqual(expectedName); 90 | }); 91 | 92 | it("should compose middleware functions", async () => { 93 | const arr: number[] = []; 94 | 95 | const fn = compose([ 96 | function(ctx: any, next: Next) { 97 | arr.push(1); 98 | 99 | return next().then(value => { 100 | arr.push(5); 101 | 102 | expect(value).toEqual("propagate"); 103 | 104 | return "done"; 105 | }); 106 | }, 107 | function(ctx: any, next: Next) { 108 | arr.push(2); 109 | 110 | return next().then(value => { 111 | arr.push(4); 112 | 113 | expect(value).toEqual("hello"); 114 | 115 | return "propagate"; 116 | }); 117 | } 118 | ]); 119 | 120 | await fn({}, () => { 121 | arr.push(3); 122 | 123 | return "hello"; 124 | }); 125 | 126 | expect(arr).toEqual([1, 2, 3, 4, 5]); 127 | }); 128 | 129 | it("branch middleware by composing", async () => { 130 | const arr: number[] = []; 131 | 132 | const fn = compose([ 133 | compose([ 134 | function(ctx: any, next: Next) { 135 | arr.push(1); 136 | 137 | return next().catch(() => { 138 | arr.push(3); 139 | }); 140 | }, 141 | function(ctx: any, next: Next) { 142 | arr.push(2); 143 | 144 | return Promise.reject(new Error("Boom!")); 145 | } 146 | ]), 147 | function(ctx: any, next: Next) { 148 | arr.push(4); 149 | 150 | return next(); 151 | } 152 | ]); 153 | 154 | await fn({}, (): void => undefined); 155 | 156 | expect(arr).toEqual([1, 2, 3]); 157 | }); 158 | }); 159 | } 160 | --------------------------------------------------------------------------------