├── .gitignore ├── .npmignore ├── .travis.yml ├── LICENSE.md ├── README.md ├── index.js ├── jest.config.js ├── lib └── index.ts ├── package.json ├── tests ├── method.test.js ├── middleware.test.js └── testing-middleware.js └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | package-lock.json 3 | index.js -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | index.ts -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 10 4 | before_script: 5 | - npm run setup 6 | - npm run build 7 | script: 8 | - npm run test -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # Released under MIT License 2 | 3 | Copyright (c) 2020 Eli Gallipoli, Sara Powers, Izumi Sato, Alex Kang. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Connext logo](https://i.ibb.co/kJpDpQG/connextlogo.png) 2 | 3 | [![Build Status](https://travis-ci.org/oslabs-beta/connext-js.svg?branch=master)](https://travis-ci.org/oslabs-beta/connext-js) 4 | 5 | A lightweight middleware and route handling solution for Next.js. Powered by [dirext](https://github.com/dirext-js/dirext) 🛸 6 | 7 | # Install connext 8 | `$ npm install connext-js` 9 | 10 | Initialize a new instance of Connext. 11 | ```javascript 12 | const Connext = require('connext-js'); 13 | const app = Connext(); 14 | ``` 15 | 16 | # Usage 17 | 18 | Connext is a middleware solution for Next.js with Express-style syntax that supports both global and flexible route-specific middleware. For global middleware, you must create a `controllers` folder that must contain a `global.js` controller file. We recommend also creating controller files for your other middleware as a way to modularize your API logic. 19 | 20 | ## Setting Routes 21 | Setting routes using `connext`closely resembles setting routes in Express. 22 | 23 | ### Method 24 | All valid HTTP request methods have associated methods on the connext object. 25 | ```javascript 26 | app.get(); 27 | app.post(); 28 | app.put(); 29 | app.delete(); 30 | app.head(); 31 | app.trace(); 32 | app.patch(); 33 | app.options(); 34 | app.connect(); 35 | ``` 36 | 37 | ### URL 38 | Connext supports any static or queried API endpoint. Support for dynamic routing is coming soon. ⚡️ 39 | 40 | ### Request & Response objects 41 | In `connext`, you have access to the **request object** available in Next.js and that access persists through the middleware chain- just like Express! The available properties are `req.url`, `req.method`, and `req.body`. 42 | 43 | Unlike Express, if you need to store data you can add any key to the **response object** with whatever data you wish to store. This will simply augment your response object and continue to persist this object throughout the lifecycle of the request. 44 | EX: 45 | ```javascript 46 | response.data = JSON.stringify(data); 47 | response.match = true; 48 | response.array = ['I'm the data you need']; 49 | ``` 50 | 51 | ## Middleware 52 | Example file structure: 53 | ``` 54 | ├── ... 55 | ├── controllers 56 | │ ├── global.js # required for global middleware 57 | │ └── middleware.js # suggested for modularization of middleware functions 58 | ├── pages # required folder for routes in Next.js 59 | │ └── api # required folder for API routes in Next.js 60 | └── ... 61 | ``` 62 | 63 | ### Global Middleware 64 | To utilize Connext's global middleware functionality, you must create a `global.js` file in a folder called `controllers`. The `controllers` folder must be at the same level as your `pages` folder and your `global.js` file must export an **array**. 65 | 66 | `connext` has a simple global built-in error handler that will run whenever something is passed into the invocation of `next()`. If you'd like to use your own error handler, define it in `global.js` as the **last** element of the exported array. 67 | 68 | **global.js example** 69 | ```javascript 70 | // a global middleware function 71 | const globalOne = (req, res, next) => { 72 | console.log('this the first function that runs!'); 73 | return next(); 74 | }; 75 | // another global middleware function 76 | const globalTwo = (req, res, next) => { 77 | console.log('another one!'); 78 | return next(); 79 | }; 80 | // global error handler 81 | const errorHandler = (err, req, res, next) => { 82 | return res.status(500).send('an error occurred'); 83 | }; 84 | // export your array of global middleware 85 | module.exports = [globalOne, globalTwo, errorHandler]; 86 | ``` 87 | 88 | We recommend that you modularize your other middleware in one or more files in your `controllers` file to keep your code readable and easy to debug 🐞 89 | 90 | **middleware.js example** 91 | ```javascript 92 | const middlewareController = {}; 93 | 94 | middlewareController.functionOne = (req, res, next) => { 95 | // middleware functionality here 96 | return next(); 97 | } 98 | 99 | middlewareController.functionTwo = (req, res, next) => { 100 | // middleware functionality here 101 | return next(); 102 | } 103 | 104 | module.exports = middlewareController; 105 | ``` 106 | 107 | ### connext.METHOD(url, [...middleware]) 108 | 109 | Like in express, every method in Connext has a string bound to it that coresponds with a valid HTTP method. 110 | 111 | For example: `GET, DELETE, POST`, etc. 112 | 113 | ## Use Case Example 114 | 115 | To define a route using Connext, add a JavaScript file inside of Next.js's required `api` folder. 116 | 117 | ``` 118 | ├── pages # required folder for routes in Next.js 119 | │ └── api # required folder for API routes in Next.js 120 | │ └── exampleRoute.js # created route file inside of API folder 121 | ``` 122 | 123 | **Inside of the route file** 124 | 125 | 1. Require in Connext and any route specific middleware controller files 126 | 2. Create a new instantiation of Connext 127 | 3. Set up routes by calling one of Connext-js's built in HTTP methods 128 | * Pass the current route in as the first argument 129 | * Chain any desired middleware functions in the order you want them to be invoked 130 | * An anonymous middleware function can be defined at the end of the middleware chain. This function will end the request cycle. 131 | 4. You can invoke multiple HTTP methods in the same route file 132 | 5. Set your Connext-js invocation as the route files export default function 133 | 134 | ``` javascript 135 | const Connext = require('Connext-js'); 136 | const middleware = require('../../controllers/middleware'); 137 | 138 | const app = Connext(); 139 | 140 | app.get('/api/exampleRoute', middleware.one, middleware.two, (req, res) => { 141 | res.status(200).json(res.example); 142 | }); 143 | app.post('/api/exampleRoute', middleware.three, (req, res) => { 144 | res.status(200).json(res.example); 145 | }); 146 | app.delete('/api/exampleRoute', middleware.four, (req, res) => { 147 | res.status(200).json(res.example); 148 | }); 149 | 150 | export default app; 151 | ``` 152 | 153 | ### Creators 154 | 155 | [Sara Powers](https://github.com/sarapowers) 156 | 157 | [Eli Gallipoli](https://github.com/egcg317) 158 | 159 | [Izumi Sato](https://github.com/izumi411) 160 | 161 | [Alex Kang](https://github.com/akang0408) 162 | 163 | 164 | 165 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const Dirext = require('dirext-js'); 2 | const fs = require('fs'); 3 | 4 | const findGlobal = () => { 5 | const globalMiddleware = []; 6 | try { 7 | if (fs.existsSync('./controllers/global.js')) { 8 | globalMiddleware.push(...require('./controllers/global.js')); 9 | } 10 | } catch (err) { 11 | console.log(err); 12 | } 13 | return globalMiddleware; 14 | }; 15 | 16 | const app = new Dirext(); 17 | 18 | module.exports = () => { 19 | function connext(req, res) { 20 | connext.invoker(req, res); 21 | } 22 | connext.routes = []; 23 | connext.globalMiddleware = findGlobal(); 24 | connext.get = set.bind(connext, 'GET'); 25 | connext.post = set.bind(connext, 'POST'); 26 | connext.put = set.bind(connext, 'PUT'); 27 | connext.patch = set.bind(connext, 'PATCH'); 28 | connext.delete = set.bind(connext, 'DELETE'); 29 | connext.head = set.bind(connext, 'HEAD'); 30 | connext.connect = set.bind(connext, 'CONNECT'); 31 | connext.options = set.bind(connext, 'OPTIONS'); 32 | connext.trace = set.bind(connext, 'TRACE'); 33 | connext.use = app.use.bind(connext); 34 | connext.routeSplitter = app.routeSplitter.bind(connext); 35 | connext.compareRoutes = app.compareRoutes.bind(connext); 36 | 37 | function set(...args) { 38 | app.set.apply(connext, args); 39 | return connext; 40 | } 41 | 42 | connext.invoker = function (req, res) { 43 | console.log('connext.routes is:', JSON.stringify(connext.routes)); 44 | console.log('hitting invoker'); 45 | // creating a variable to store user's exported array of global middleware functions 46 | // defining an error handler that can be overwritten if the user creates their own global error handling function 47 | let errorHandler = (err, req, res, next) => { 48 | res.status(500).send(`err: ${err}`); 49 | }; 50 | // if the global middleware array exists and the last function in the array accepts 4 arguments (catch all error route), set errorHandler to that last function 51 | if (connext.globalMiddleware[connext.globalMiddleware.length - 1].length === 4) { 52 | errorHandler = connext.globalMiddleware.pop(); 53 | } 54 | // if the global middleware array is not empty set const middleware to that array, otherwise set const middleware to an empty array 55 | let middleware = []; 56 | // deconstruct method and url out of req 57 | const { method, url } = req; 58 | // invoke this.find with method and url passed in as arguments at the key 'middleware' and set that to const targetMiddleware 59 | const targetMiddleware = app.find.apply(connext, [method, url]).middleware; 60 | console.log('targetMiddleware is: ', targetMiddleware); 61 | // push the spread array targetMiddleware into middleware array 62 | middleware.push(...connext.globalMiddleware, ...targetMiddleware); 63 | // counter to keep track of position of current middleware function 64 | console.log('middleware array is: ', middleware); 65 | let i = 0; 66 | // loop through middleware array and invoke each function in order. if an error is passed into next function return that error. 67 | async function next(err) { 68 | if (err) return errorHandler(err, req, res); 69 | // eslint-disable-next-line no-useless-catch 70 | while (i < middleware.length) { 71 | try { 72 | const currentMiddleware = middleware[i]; 73 | if (i === middleware.length - 1) { 74 | middleware = []; 75 | } 76 | i += 1; 77 | return currentMiddleware(req, res, next); 78 | } catch (error) { 79 | return error; 80 | } 81 | } 82 | console.log('middleware after splice is:', middleware); 83 | } 84 | return next(); 85 | }; 86 | return connext; 87 | }; 88 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | // For a detailed explanation regarding each configuration property, visit: 2 | // https://jestjs.io/docs/en/configuration.html 3 | 4 | module.exports = { 5 | // All imported modules in your tests should be mocked automatically 6 | // automock: false, 7 | 8 | // Stop running tests after `n` failures 9 | // bail: 0, 10 | 11 | // Respect "browser" field in package.json when resolving modules 12 | // browser: false, 13 | 14 | // The directory where Jest should store its cached dependency information 15 | // cacheDirectory: "/private/var/folders/mn/rdyx1f3x1_190xq31xbtq6rr0000gp/T/jest_dy", 16 | 17 | // Automatically clear mock calls and instances between every test 18 | clearMocks: true, 19 | 20 | // Indicates whether the coverage information should be collected while executing the test 21 | // collectCoverage: false, 22 | 23 | // An array of glob patterns indicating a set of files for which coverage information should be collected 24 | // collectCoverageFrom: null, 25 | 26 | // The directory where Jest should output its coverage files 27 | coverageDirectory: "coverage", 28 | 29 | // An array of regexp pattern strings used to skip coverage collection 30 | // coveragePathIgnorePatterns: [ 31 | // "/node_modules/" 32 | // ], 33 | 34 | // A list of reporter names that Jest uses when writing coverage reports 35 | // coverageReporters: [ 36 | // "json", 37 | // "text", 38 | // "lcov", 39 | // "clover" 40 | // ], 41 | 42 | // An object that configures minimum threshold enforcement for coverage results 43 | // coverageThreshold: null, 44 | 45 | // A path to a custom dependency extractor 46 | // dependencyExtractor: null, 47 | 48 | // Make calling deprecated APIs throw helpful error messages 49 | // errorOnDeprecated: false, 50 | 51 | // Force coverage collection from ignored files using an array of glob patterns 52 | // forceCoverageMatch: [], 53 | 54 | // A path to a module which exports an async function that is triggered once before all test suites 55 | // globalSetup: null, 56 | 57 | // A path to a module which exports an async function that is triggered once after all test suites 58 | // globalTeardown: null, 59 | 60 | // A set of global variables that need to be available in all test environments 61 | // globals: {}, 62 | 63 | // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. 64 | // maxWorkers: "50%", 65 | 66 | // An array of directory names to be searched recursively up from the requiring module's location 67 | // moduleDirectories: [ 68 | // "node_modules" 69 | // ], 70 | 71 | // An array of file extensions your modules use 72 | moduleFileExtensions: [ 73 | "js", 74 | "json", 75 | "jsx", 76 | // "ts", 77 | // "tsx", 78 | "node" 79 | ], 80 | 81 | // A map from regular expressions to module names that allow to stub out resources with a single module 82 | // moduleNameMapper: {}, 83 | 84 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader 85 | modulePathIgnorePatterns: ['/tests/testing-middleware.js'], 86 | 87 | // Activates notifications for test results 88 | // notify: false, 89 | 90 | // An enum that specifies notification mode. Requires { notify: true } 91 | // notifyMode: "failure-change", 92 | 93 | // A preset that is used as a base for Jest's configuration 94 | // preset: null, 95 | 96 | // Run tests from one or more projects 97 | // projects: null, 98 | 99 | // Use this configuration option to add custom reporters to Jest 100 | // reporters: undefined, 101 | 102 | // Automatically reset mock state between every test 103 | // resetMocks: false, 104 | 105 | // Reset the module registry before running each individual test 106 | // resetModules: false, 107 | 108 | // A path to a custom resolver 109 | // resolver: null, 110 | 111 | // Automatically restore mock state between every test 112 | // restoreMocks: false, 113 | 114 | // The root directory that Jest should scan for tests and modules within 115 | // rootDir: null, 116 | 117 | // A list of paths to directories that Jest should use to search for files in 118 | // roots: [ 119 | // "" 120 | // ], 121 | 122 | // Allows you to use a custom runner instead of Jest's default test runner 123 | // runner: "jest-runner", 124 | 125 | // The paths to modules that run some code to configure or set up the testing environment before each test 126 | // setupFiles: [], 127 | 128 | // A list of paths to modules that run some code to configure or set up the testing framework before each test 129 | // setupFilesAfterEnv: [], 130 | 131 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing 132 | // snapshotSerializers: [], 133 | 134 | // The test environment that will be used for testing 135 | testEnvironment: "node", 136 | 137 | // Options that will be passed to the testEnvironment 138 | // testEnvironmentOptions: {}, 139 | 140 | // Adds a location field to test results 141 | // testLocationInResults: false, 142 | 143 | // The glob patterns Jest uses to detect test files 144 | // testMatch: [ 145 | // "**/__tests__/**/*.[jt]s?(x)", 146 | // "**/?(*.)+(spec|test).[tj]s?(x)" 147 | // ], 148 | 149 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped 150 | // testPathIgnorePatterns: [ 151 | // "/node_modules/" 152 | // ], 153 | 154 | // The regexp pattern or array of patterns that Jest uses to detect test files 155 | testRegex: ['(/tests/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$'], 156 | 157 | // This option allows the use of a custom results processor 158 | // testResultsProcessor: null, 159 | 160 | // This option allows use of a custom test runner 161 | // testRunner: "jasmine2", 162 | 163 | // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href 164 | // testURL: "http://localhost", 165 | 166 | // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" 167 | // timers: "real", 168 | 169 | // A map from regular expressions to paths to transformers 170 | transform: { 171 | '^.+\\.tsx?$': 'ts-jest', 172 | }, 173 | 174 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation 175 | // transformIgnorePatterns: [ 176 | // "/node_modules/" 177 | // ], 178 | 179 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them 180 | // unmockedModulePathPatterns: undefined, 181 | 182 | // Indicates whether each individual test should be reported during the run 183 | // verbose: null, 184 | 185 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode 186 | // watchPathIgnorePatterns: [], 187 | 188 | // Whether to use watchman for file crawling 189 | // watchman: true, 190 | }; 191 | -------------------------------------------------------------------------------- /lib/index.ts: -------------------------------------------------------------------------------- 1 | const Dirext = require('dirext-js'); 2 | const fs = require('fs'); 3 | 4 | const findGlobal = () => { 5 | const globalMiddleware = []; 6 | try { 7 | if (fs.existsSync('../../controllers/global.js')) { 8 | globalMiddleware.push(...require('../../controllers/global.js')); 9 | } 10 | } catch (err) { 11 | console.log(err); 12 | } 13 | return globalMiddleware; 14 | }; 15 | 16 | const app = new Dirext(); 17 | 18 | module.exports = () => { 19 | function connext(req: object, res: object) { 20 | connext.invoker(req, res); 21 | } 22 | connext.routes = []; 23 | connext.globalMiddleware = findGlobal(); 24 | connext.get = set.bind(connext, 'GET'); 25 | connext.post = set.bind(connext, 'POST'); 26 | connext.put = set.bind(connext, 'PUT'); 27 | connext.patch = set.bind(connext, 'PATCH'); 28 | connext.delete = set.bind(connext, 'DELETE'); 29 | connext.head = set.bind(connext, 'HEAD'); 30 | connext.connect = set.bind(connext, 'CONNECT'); 31 | connext.options = set.bind(connext, 'OPTIONS'); 32 | connext.trace = set.bind(connext, 'TRACE'); 33 | connext.use = app.use.bind(connext); 34 | connext.routeSplitter = app.routeSplitter.bind(connext); 35 | connext.compareRoutes = app.compareRoutes.bind(connext); 36 | 37 | function set(...args) { 38 | app.set.apply(connext, args); 39 | return connext; 40 | } 41 | 42 | connext.invoker = function (req: object, res: object) { 43 | // creating a variable to store user's exported array of global middleware functions 44 | // defining an error handler that can be overwritten if the user creates their own global error handling function 45 | let errorHandler = (err: object, req: object, res: object, next: object) => { 46 | // @ts-ignore 47 | res.status(500).send(`err: ${err}`); 48 | }; 49 | // if the global middleware array exists and the last function in the array accepts 4 arguments (catch all error route), set errorHandler to that last function 50 | if (connext.globalMiddleware.length > 0 && connext.globalMiddleware[connext.globalMiddleware.length - 1].length === 4) { 51 | errorHandler = connext.globalMiddleware.pop(); 52 | } 53 | // if the global middleware array is not empty set const middleware to that array, otherwise set const middleware to an empty array 54 | let middleware = []; 55 | // deconstruct method and url out of req 56 | // @ts-ignore 57 | const { method, url } = req; 58 | // invoke this.find with method and url passed in as arguments at the key 'middleware' and set that to const targetMiddleware 59 | const targetMiddleware = app.find.apply(connext, [method, url]).middleware; 60 | // push the spread array targetMiddleware into middleware array 61 | middleware.push(...connext.globalMiddleware, ...targetMiddleware); 62 | // counter to keep track of position of current middleware function 63 | let i = 0; 64 | // loop through middleware array and invoke each function in order. if an error is passed into next function return that error. 65 | // @ts-ignore 66 | 67 | async function next(err: object) { 68 | if (err) return errorHandler(err, req, res, next); 69 | // eslint-disable-next-line no-useless-catch 70 | while (i < middleware.length) { 71 | try { 72 | const currentMiddleware = middleware[i]; 73 | if (i === middleware.length - 1) { 74 | middleware = []; 75 | } 76 | i += 1; 77 | return currentMiddleware(req, res, next); 78 | } catch (error) { 79 | return error; 80 | } 81 | } 82 | } 83 | // @ts-ignore 84 | if (middleware[0]) return next(); 85 | return; 86 | }; 87 | return connext; 88 | }; 89 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "connext-js", 3 | "version": "1.1.0", 4 | "description": "A middleware and route handling solution for Next.js.", 5 | "main": "./lib/index.js", 6 | "types": "index.d.ts", 7 | "scripts": { 8 | "setup": "npm install", 9 | "build": "tsc lib/index.ts", 10 | "test": "jest" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/oslabs-beta/connext-js.git" 15 | }, 16 | "authors": "Sara Powers, Eli Gallipoli, Alex Kang, Izumi Sato", 17 | "license": "MIT", 18 | "bugs": { 19 | "url": "https://github.com/oslabs-beta/connext-js/issues" 20 | }, 21 | "homepage": "https://github.com/oslabs-beta/connext-js#readme", 22 | "keywords": [ 23 | "next-js", 24 | "global", 25 | "middleware", 26 | "express", 27 | "routing", 28 | "router", 29 | "route", 30 | "next", 31 | "API", 32 | "API routes", 33 | "chainable", 34 | "lightweight", 35 | "flexible", 36 | "custom" 37 | ], 38 | "dependencies": { 39 | "@types/node": "^13.7.6", 40 | "dirext-js": "^1.0.6" 41 | }, 42 | "devDependencies": { 43 | "typescript": "^3.8.2", 44 | "jest": "^25.1.0", 45 | "ts-jest": "^25.2.1" 46 | }, 47 | "prepublish": "tsc" 48 | } 49 | -------------------------------------------------------------------------------- /tests/method.test.js: -------------------------------------------------------------------------------- 1 | /*eslint-disable*/ 2 | const Connext = require('../lib/index.js'); 3 | 4 | const connext = Connext(); 5 | 6 | describe('connext method tests', () => { 7 | describe('connext initialization testing', () => { 8 | it('routes should initialize as an empty array', () => { 9 | expect(connext.routes).toEqual([]); 10 | }); 11 | 12 | it('connext should have all methods', () => { 13 | expect(connext.get).toBeTruthy(); 14 | expect(connext.post).toBeTruthy(); 15 | expect(connext.put).toBeTruthy(); 16 | expect(connext.patch).toBeTruthy(); 17 | expect(connext.delete).toBeTruthy(); 18 | expect(connext.head).toBeTruthy(); 19 | expect(connext.connect).toBeTruthy(); 20 | expect(connext.options).toBeTruthy(); 21 | expect(connext.trace).toBeTruthy(); 22 | expect(connext.use).toBeTruthy(); 23 | expect(connext.routeSplitter).toBeTruthy(); 24 | expect(connext.compareRoutes).toBeTruthy(); 25 | }); 26 | }); 27 | 28 | describe('static route testing', () => { 29 | afterEach(() => { 30 | connext.routes = []; 31 | }); 32 | 33 | it('GET method should add static routes', () => { 34 | connext.get('/api/staticRoute', () => 'middleware 1'); 35 | expect(connext.routes.length).toBe(1); 36 | expect(typeof connext.routes[0]).toBe('object'); 37 | expect(connext.routes[0].method).toBe('GET'); 38 | expect(connext.routes[0].url).toEqual([{ route: 'api' }, { route: 'staticRoute' }]); 39 | expect(connext.routes[0].middleware.length).toBe(1); 40 | }); 41 | 42 | it('POST method should add static routes', () => { 43 | connext.post('/api/staticRoute', () => 'middleware 1'); 44 | expect(connext.routes.length).toBe(1); 45 | expect(typeof connext.routes[0]).toBe('object'); 46 | expect(connext.routes[0].method).toBe('POST'); 47 | expect(connext.routes[0].url).toEqual([{ route: 'api' }, { route: 'staticRoute' }]); 48 | expect(connext.routes[0].middleware.length).toBe(1); 49 | }); 50 | 51 | it('DELETE method should add static routes', () => { 52 | connext.delete('/api/staticRoute', () => 'middleware 1'); 53 | expect(connext.routes.length).toBe(1); 54 | expect(typeof connext.routes[0]).toBe('object'); 55 | expect(connext.routes[0].method).toBe('DELETE'); 56 | expect(connext.routes[0].url).toEqual([{ route: 'api' }, { route: 'staticRoute' }]); 57 | expect(connext.routes[0].middleware.length).toBe(1); 58 | }); 59 | 60 | it('PUT method should add static routes', () => { 61 | connext.put('/api/staticRoute', () => 'middleware 1'); 62 | expect(connext.routes.length).toBe(1); 63 | expect(typeof connext.routes[0]).toBe('object'); 64 | expect(connext.routes[0].method).toBe('PUT'); 65 | expect(connext.routes[0].url).toEqual([{ route: 'api' }, { route: 'staticRoute' }]); 66 | expect(connext.routes[0].middleware.length).toBe(1); 67 | }); 68 | 69 | it('PATCH method should add static routes', () => { 70 | connext.patch('/api/staticRoute', () => 'middleware 1'); 71 | expect(connext.routes.length).toBe(1); 72 | expect(typeof connext.routes[0]).toBe('object'); 73 | expect(connext.routes[0].method).toBe('PATCH'); 74 | expect(connext.routes[0].url).toEqual([{ route: 'api' }, { route: 'staticRoute' }]); 75 | expect(connext.routes[0].middleware.length).toBe(1); 76 | }); 77 | 78 | it('USE method should add static routes', () => { 79 | connext.use('/api/staticRoute', () => 'middleware 1'); 80 | expect(connext.routes.length).toBe(1); 81 | expect(typeof connext.routes[0]).toBe('object'); 82 | expect(connext.routes[0].method).toBe(''); 83 | expect(connext.routes[0].url).toEqual([{ route: 'api' }, { route: 'staticRoute' }]); 84 | expect(connext.routes[0].middleware.length).toBe(1); 85 | }); 86 | }); 87 | 88 | describe('parameterized route testing', () => { 89 | afterEach(() => { 90 | connext.routes = []; 91 | }); 92 | 93 | it('should handle single parameterized endpoint', () => { 94 | connext.get('/api/:id', () => 'middleware 1'); 95 | expect(connext.routes.length).toBe(1); 96 | expect(connext.routes[0].url[1].param).toBeTruthy(); 97 | expect(connext.routes[0].url[1].param).toBe('id'); 98 | }); 99 | 100 | it('should handle nested parameterized endpoints', () => { 101 | connext.get('/api/:id/:name', () => 'middleware 1'); 102 | expect(connext.routes.length).toBe(1); 103 | expect(connext.routes[0].url.length).toBe(3); 104 | expect(connext.routes[0].url[1].param).toBe('id'); 105 | expect(connext.routes[0].url[2].param).toBe('name'); 106 | }); 107 | 108 | it('should handle non-consecutive parameters', () => { 109 | connext.get('/api/:id/user/:name', () => 'middleware 1'); 110 | expect(connext.routes.length).toBe(1); 111 | expect(connext.routes[0].url.length).toBe(4); 112 | expect(connext.routes[0].url[1].param).toBe('id'); 113 | expect(connext.routes[0].url[2].route).toBeTruthy(); 114 | expect(connext.routes[0].url[2].route).toBe('user'); 115 | expect(connext.routes[0].url[3].param).toBe('name'); 116 | }); 117 | }); 118 | }); 119 | -------------------------------------------------------------------------------- /tests/middleware.test.js: -------------------------------------------------------------------------------- 1 | // /*eslint-disable*/ 2 | const Connext = require('../lib/index.js'); 3 | const middleware = require('./testing-middleware.js'); 4 | 5 | const connext = Connext(); 6 | 7 | describe('connext middleware testing', () => { 8 | describe('single middleware function testing', () => { 9 | afterEach(() => { 10 | connext.routes = []; 11 | }); 12 | 13 | it('should execute anonymous middleware', () => { 14 | const req = { method: 'DELETE', url: '/api/test' }; 15 | const res = {}; 16 | let result = 0; 17 | connext.delete('/api/test', (req, res, next) => { 18 | res.num = 10; 19 | result = res.num; 20 | }); 21 | connext(req, res); 22 | expect(result).toEqual(10); 23 | }); 24 | 25 | it('should update the response body given a single middleware function', () => { 26 | const req = { method: 'POST', url: '/api/test' }; 27 | const res = {}; 28 | let result = 0; 29 | connext.post('/api/test', middleware.addTwo, (req, res, next) => { 30 | result = res.num; 31 | }); 32 | connext(req, res); 33 | expect(result).toEqual(2); 34 | }); 35 | 36 | it('should update the response body given a different single middleware function', () => { 37 | const req = { method: 'POST', url: '/api/test' }; 38 | const res = {}; 39 | let result = 0; 40 | connext.post('/api/test', middleware.timesTwo, (req, res, next) => { 41 | result = res.num; 42 | }); 43 | connext(req, res); 44 | expect(result).toEqual(4); 45 | }); 46 | }); 47 | 48 | describe('chained middleware function testing', () => { 49 | afterEach(() => { 50 | connext.routes = []; 51 | }); 52 | 53 | it('should persist request and response through chained middleware calls', () => { 54 | const req = { method: 'GET', url: '/api/test' }; 55 | const res = {}; 56 | let result = 0; 57 | connext.get('/api/test', middleware.addTwo, middleware.timesTwo, (req, res, next) => { 58 | result = res.num; 59 | }); 60 | connext(req, res); 61 | expect(result).toEqual(4); 62 | }); 63 | 64 | it('should persist request and response through different chained middleware calls', () => { 65 | const req = { method: 'PATCH', url: '/api/test' }; 66 | const res = {}; 67 | let result = 0; 68 | connext.patch('/api/test', middleware.minusTwo, middleware.dividedTwo, (req, res, next) => { 69 | result = res.num; 70 | }); 71 | connext(req, res); 72 | expect(result).toEqual(1); 73 | }); 74 | 75 | it('should persist request and response through multiple middleware and anonymous function calls', () => { 76 | const req = { method: 'TRACE', url: '/api/test' }; 77 | const res = {}; 78 | let result = 0; 79 | connext.trace('/api/test', middleware.minusTwo, middleware.dividedTwo, (req, res, next) => { 80 | res.num += 1000; 81 | result = res.num; 82 | }); 83 | connext(req, res); 84 | expect(result).toEqual(1001); 85 | 86 | }); 87 | }); 88 | }); 89 | -------------------------------------------------------------------------------- /tests/testing-middleware.js: -------------------------------------------------------------------------------- 1 | const middleware = {}; 2 | 3 | middleware.addTwo = (req, res, next) => { 4 | console.log('add two is running'); 5 | if (res.num) res.num += 2; 6 | else res.num = 2; 7 | return next(); 8 | }; 9 | 10 | middleware.timesTwo = (req, res, next) => { 11 | if (res.num) res.num *= 2; 12 | else res.num = 4; 13 | return next(); 14 | }; 15 | 16 | middleware.dividedTwo = (req, res, next) => { 17 | if (res.num) res.num /= 2; 18 | else res.num = 2; 19 | return next(); 20 | }; 21 | 22 | middleware.minusTwo = (req, res, next) => { 23 | if (res.num) res.num -= 2; 24 | else res.num = 2; 25 | return next(); 26 | }; 27 | 28 | module.exports = middleware; 29 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | // "incremental": true, /* Enable incremental compilation */ 5 | "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ 6 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 7 | // "lib": [], /* Specify library files to be included in the compilation. */ 8 | // "allowJs": true, /* Allow javascript files to be compiled. */ 9 | // "checkJs": true, /* Report errors in .js files. */ 10 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 11 | "declaration": true, /* Generates corresponding '.d.ts' file. */ 12 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 13 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 14 | // "outFile": "./", /* Concatenate and emit output to single file. */ 15 | // "outDir": "./", /* Redirect output structure to the directory. */ 16 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 17 | // "composite": true, /* Enable project compilation */ 18 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 19 | // "removeComments": true, /* Do not emit comments to output. */ 20 | // "noEmit": true, /* Do not emit outputs. */ 21 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 22 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 23 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 24 | 25 | /* Strict Type-Checking Options */ 26 | "strict": true, /* Enable all strict type-checking options. */ 27 | // "noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */ 28 | // "strictNullChecks": true, /* Enable strict null checks. */ 29 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 30 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 31 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 32 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 33 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 34 | 35 | /* Additional Checks */ 36 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 37 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 38 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 39 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 40 | 41 | /* Module Resolution Options */ 42 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 43 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 44 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 45 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 46 | // "typeRoots": [], /* List of folders to include type definitions from. */ 47 | // "types": [], /* Type declaration files to be included in compilation. */ 48 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 49 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 50 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 51 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 52 | 53 | /* Source Map Options */ 54 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 55 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 56 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 57 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 58 | 59 | /* Experimental Options */ 60 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 61 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 62 | 63 | /* Advanced Options */ 64 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 65 | } 66 | } 67 | --------------------------------------------------------------------------------