Add own callback for notFound

This commit is contained in:
Michael Bykovski 2017-07-25 22:09:56 +02:00
parent 7b9fad3090
commit d79671b0c9
2 changed files with 25 additions and 9 deletions

View File

@ -11,9 +11,9 @@ export default class AppServer {
// Why? because SOLID of this class // Why? because SOLID of this class
this.webserver = webserver; this.webserver = webserver;
this.routes = []; this.routes = [];
this.notFoundCallback = null;
this.onRequest = this.onRequest.bind(this); this.onRequest = this.onRequest.bind(this);
this.initWebserver(); this.initWebserver();
this.initRouter(); this.initRouter();
} }
@ -30,12 +30,21 @@ export default class AppServer {
this.routes.push( this.routes.push(
{ {
path: path, path: path,
action: () => callback action: (context) => {
return {
callback: callback,
context: context
};
}
} }
); );
this.initRouter(); this.initRouter();
} }
addNotFound(callback) {
this.notFoundCallback = callback;
}
onRequest(request) { onRequest(request) {
let requestObject = new Request( let requestObject = new Request(
request.requestId, request.requestId,
@ -55,14 +64,19 @@ export default class AppServer {
requestObject.path requestObject.path
).then( ).then(
// callback is a function // callback is a function
(callback) => { (callbackContext) => {
// run the callback with all information we got for the request and the response // run the callback with all information we got for the request and the response
callback(requestObject, responseObject); requestObject.params = callbackContext.context.params;
callbackContext.callback(requestObject, responseObject);
} }
).catch( ).catch(
(error) => { (error) => {
// if there is an error, just send a not found 404 bljad if (!this.notFoundCallback) {
responseObject.notFound(); // if there is an error, just send a not found 404 bljad
responseObject.notFound();
} else {
this.notFoundCallback();
}
} }
); );
} }

View File

@ -14,6 +14,8 @@ export default class Response {
this.status = status; this.status = status;
this.body = body; this.body = body;
this.headers = headers; this.headers = headers;
this.send = this.send.bind(this);
} }
send() { send() {
@ -34,15 +36,15 @@ export default class Response {
} }
notFound(){ notFound(){
return this.status(404).send(); this.status(404).send();
} }
methodNotAllowed() { methodNotAllowed() {
return this.status(405).send(); this.status(405).send();
} }
ok() { ok() {
return this.status(200).send(); this.status(200).send();
} }
setHeader(key, value) { setHeader(key, value) {