Skip to content

Commit a1fb695

Browse files
committed
Added crude support for route middleware. Tested with multer file upload
1 parent 6edaaae commit a1fb695

File tree

11 files changed

+265
-4
lines changed

11 files changed

+265
-4
lines changed

package-lock.json

Lines changed: 174 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"consolidate": "^0.15.1",
1515
"ejs": "^2.6.1",
1616
"morgan": "^1.9.1",
17+
"multer": "^1.4.2",
1718
"nodemon": "^2.0.3",
1819
"serve-static": "^1.13.2"
1920
}

src/lib/application.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ class App {
2020
init() {
2121
// Create method on the instance of app
2222
this.methods.forEach(method => {
23-
this[method.toLowerCase()] = (path, callback) => {
23+
//todo: param as arrays (last function being the callback)
24+
this[method.toLowerCase()] = (path, ...callback) => {
2425
this.router.route(method, path, callback);
2526
};
2627
});

src/lib/router/index.js

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,13 @@ class Router {
2525
})
2626
}
2727

28-
route(method, url, callback) {
28+
route(method, url, callback) {
29+
console.log("ARGS: MIDDLEWARE: ", url, callback);
2930
let routes = this.routes[method.toLowerCase()]; // There can be more than one route matching
3031
routes.push({
3132
path: url,
32-
callback: callback
33+
middlewares: callback.slice(0,callback.length-1),
34+
callback: callback[callback.length-1] // last param
3335
});
3436
}
3537

@@ -58,6 +60,7 @@ class Router {
5860
console.log("NURL: ", url);
5961

6062
let matchedRoute = this.match(url, method);
63+
console.log("matchedRoute: ", matchedRoute);
6164

6265
if (!matchedRoute) {
6366
return res.notFound().end("Not found!");
@@ -66,6 +69,12 @@ class Router {
6669
// Setup request-> todo
6770
req = this._setupRequestParams(req, matchedRoute.params, matchedRoute.query);
6871

72+
// If route has middleware call it
73+
matchedRoute.match.middlewares.forEach(m => {
74+
console.log("CALLING ROUTE:MIDDLEWARES: ",m);
75+
m(req, res, () => {});
76+
});
77+
6978
// TODO:
7079
if (method == "get" || method == "delete") { // get, delete etc
7180
matchedRoute.match.callback(req, res);
@@ -108,7 +117,12 @@ class Router {
108117

109118
//TODO: NEED WORK HERE
110119
if (postedData && postedData.indexOf('{') > -1) {
111-
req.body = JSON.parse(postedData);
120+
try {
121+
req.body = JSON.parse(postedData);
122+
} catch(e) {
123+
req.body = postedData;
124+
req.file = postedData;
125+
}
112126
} else {
113127
req.body = postedData;
114128
}

0 commit comments

Comments
 (0)