diff --git a/.gitignore b/.gitignore index 346bd84..b1725a8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,6 @@ -# Dependency directories node_modules - -# Optional npm cache directory .npm - -# Local REDIS test data dump.rdb - -# Coverage reports .nyc_output coverage +.idea diff --git a/__tests__/basePath.unit.js b/__tests__/basePath.unit.js index 5e8fc5e..e093b4a 100644 --- a/__tests__/basePath.unit.js +++ b/__tests__/basePath.unit.js @@ -1,7 +1,5 @@ 'use strict'; - - // Init API instance const api = require('../index')({ version: 'v1.0', base: '/v1' }) @@ -17,9 +15,21 @@ let event = { } } +api.use(function (req, res, next) { + console.log('HELLO FROM MIDDLEWARE') + req.testMiddleware = "123"; + next(); +}); + /******************************************************************************/ /*** DEFINE TEST ROUTES ***/ /******************************************************************************/ +api.get("/", function(req, res) { + res.status(200).json({ + testMiddleware: req.testMiddleware, + }) +}); + api.get('/test', function(req,res) { res.status(200).json({ method: 'get', status: 'ok' }) }) @@ -39,6 +49,11 @@ api.get('/test/test2/test3', function(req,res) { /******************************************************************************/ describe('Base Path Tests:', function() { + it('should return testMiddleware: 123 when calling the root path', async function() { + let _event = Object.assign({},event,{ path: '/v1' }) + let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) })) + expect(result).toEqual({ multiValueHeaders: { 'content-type': ['application/json'] }, statusCode: 200, body: '{"testMiddleware":"123"}', isBase64Encoded: false }) + }) it('Simple path with base: /v1/test', async function() { let _event = Object.assign({},event,{ path: '/v1/test' }) diff --git a/__tests__/middleware.unit.js b/__tests__/middleware.unit.js index 868b0b3..796e341 100644 --- a/__tests__/middleware.unit.js +++ b/__tests__/middleware.unit.js @@ -144,6 +144,23 @@ api9.use(middleware3); /*** DEFINE TEST ROUTES ***/ /******************************************************************************/ +api.get("/", function(req, res) { + res.status(200).json({ + testMiddleware: req.testMiddleware, + }) +}); +api.post("/", function(req, res) { + res.status(200).json({ + testMiddleware2: req.testMiddleware2, + }) +}); +api.any("/", function(req, res) { + res.status(200).json({ + testMiddleware: req.testMiddleware, + testMiddleware2: req.testMiddleware2, + }) +}); + api.get("/test", function (req, res) { res.status(200).json({ method: "get", @@ -327,6 +344,51 @@ api9.get("/data/test", (req, res) => { describe("Middleware Tests:", function () { // this.slow(300); + it('should return testMiddleware: 123 when calling the root route with GET', async function () { + let _event = Object.assign({}, event, {path: "/"}); + let result = await new Promise((r) => + api.run(_event, {}, (e, res) => { + r(res); + }) + ); + expect(result).toEqual({ + multiValueHeaders: { "content-type": ["application/json"] }, + statusCode: 200, + body: '{"testMiddleware":"123"}', + isBase64Encoded: false, + }); + }) + + it('should return testMiddleware2: 456 when calling the root route with POST', async function () { + let _event = Object.assign({}, event, {path: "/", httpMethod: "POST"}); + let result = await new Promise((r) => + api.run(_event, {}, (e, res) => { + r(res); + }) + ); + expect(result).toEqual({ + multiValueHeaders: { "content-type": ["application/json"] }, + statusCode: 200, + body: '{"testMiddleware2":"456"}', + isBase64Encoded: false, + }); + }) + + it('should return testMiddleware: 123 when calling the root route with PATCH', async function () { + let _event = Object.assign({}, event, {path: "/", httpMethod: "PATCH"}); + let result = await new Promise((r) => + api.run(_event, {}, (e, res) => { + r(res); + }) + ); + expect(result).toEqual({ + multiValueHeaders: { "content-type": ["application/json"] }, + statusCode: 200, + body: '{"testMiddleware":"123","testMiddleware2":"456"}', + isBase64Encoded: false, + }); + }) + it("Set Values in res object", async function () { let _event = Object.assign({}, event, {}); let result = await new Promise((r) => diff --git a/index.js b/index.js index 86e3439..54cf518 100644 --- a/index.js +++ b/index.js @@ -144,13 +144,8 @@ class API { route.push(''); } - // Keep track of path variables let pathVars = {}; - - // Make a local copy of routes let routes = this._routes; - - // Create a local stack for inheritance let _stack = { '*': [], m: [] }; // Loop through the path levels @@ -178,20 +173,17 @@ class API { methods.forEach((_method) => { // Method must be a string if (typeof _method === 'string') { - // Check for wild card at this level - if (routes['ROUTES']['*']) { + const wildcardForPathLevel = routes[i] == '' ? routes['ROUTES']['*'] : routes['ROUTES'][route[i]]['*']; + if (wildcardForPathLevel != null) { if ( - routes['ROUTES']['*']['MIDDLEWARE'] && + wildcardForPathLevel['MIDDLEWARE'] && (route[i] !== '*' || _method !== '__MW__') ) { - _stack['*'][method] = routes['ROUTES']['*']['MIDDLEWARE'].stack; + _stack['*'][method] = wildcardForPathLevel['MIDDLEWARE'].stack; } - if ( - routes['ROUTES']['*']['METHODS'] && - routes['ROUTES']['*']['METHODS'][method] - ) { + if (wildcardForPathLevel?.['METHODS']?.[method] != null) { _stack['m'][method] = - routes['ROUTES']['*']['METHODS'][method].stack; + wildcardForPathLevel['METHODS'][method].stack; } } // end if wild card @@ -215,13 +207,12 @@ class API { : _stack['*'][method] ? _stack['*'][method].concat(stack) : stack, - // inherited: _stack[method] ? _stack[method] : [], route: '/' + parsedPath.join('/'), path: '/' + this._prefix.concat(parsedPath).join('/'), }; - // If mounting middleware - if (method === '__MW__') { + const isMountingMiddleware = _method === '__MW__'; + if (isMountingMiddleware) { // Merge stacks if middleware exists if (routes['ROUTES'][route[i]]['MIDDLEWARE']) { meta.stack = @@ -233,17 +224,6 @@ class API { } // Add/update middleware routes['ROUTES'][route[i]]['MIDDLEWARE'] = meta; - - // Apply middleware to all child middlware routes - // if (route[i] === "*") { - // // console.log("APPLY NESTED MIDDLEWARE"); - // // console.log(JSON.stringify(routes["ROUTES"], null, 2)); - // Object.keys(routes["ROUTES"]).forEach((nestedRoute) => { - // if (nestedRoute != "*") { - // console.log(nestedRoute); - // } - // }); - // } } else { // Create the methods section if it doesn't exist if (!routes['ROUTES'][route[i]]['METHODS']) @@ -265,8 +245,6 @@ class API { routes['ROUTES'][route[i]]['METHODS'][_method] = meta; } // end else - // console.log('STACK:',meta); - // If there's a wild card that's not at the end } else if (route[i] === '*') { throw new ConfigurationError(