Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(middleware): allow usage of basePath in index route #227

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 1 addition & 7 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -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
19 changes: 17 additions & 2 deletions __tests__/basePath.unit.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
'use strict';



// Init API instance
const api = require('../index')({ version: 'v1.0', base: '/v1' })

Expand All @@ -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' })
})
Expand All @@ -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' })
Expand Down
62 changes: 62 additions & 0 deletions __tests__/middleware.unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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) =>
Expand Down
38 changes: 8 additions & 30 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand All @@ -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 =
Expand All @@ -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'])
Expand All @@ -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(
Expand Down
Loading