diff --git a/src/www/appserver/AppServer.js b/src/www/appserver/AppServer.js index b5f8cd0..c8f15f3 100644 --- a/src/www/appserver/AppServer.js +++ b/src/www/appserver/AppServer.js @@ -1,3 +1,5 @@ +/*global webserver*/ + import UniversalRouter from 'universal-router'; import Request from "./Request"; import Response from "./Response"; @@ -9,19 +11,21 @@ export default class AppServer { // Why? because SOLID of this class this.webserver = webserver; this.routes = []; - + + this.onRequest = this.onRequest.bind(this); + this.initWebserver(); this.initRouter(); } - + initWebserver() { this.webserver.onRequest(this.onRequest); } - + initRouter() { this.router = new UniversalRouter(this.routes); } - + addRoute(path, callback) { this.routes.push( { @@ -31,24 +35,24 @@ export default class AppServer { ); this.initRouter(); } - + onRequest(request) { let requestObject = new Request( request.requestId, request.method, - request.path, - request.query, request.body, - request.headers + request.headers, + request.path, + request.query ); - + let responseObject = new Response( this.webserver, requestObject.requestId ); - + this.router.resolve( - requestObject.url + requestObject.path ).then( // callback is a function (callback) => { @@ -62,12 +66,12 @@ export default class AppServer { } ); } - + start() { this.webserver.start(); } - + stop() { this.webserver.stop(); } -} \ No newline at end of file +} diff --git a/src/www/appserver/Response.js b/src/www/appserver/Response.js index 226d09f..601b0fa 100644 --- a/src/www/appserver/Response.js +++ b/src/www/appserver/Response.js @@ -1,5 +1,5 @@ - export default class Response { + constructor( webserver, requestId, @@ -15,7 +15,7 @@ export default class Response { this.body = body; this.headers = headers; } - + send() { this.webserver.sendResponse( { @@ -26,26 +26,32 @@ export default class Response { ); return this; } - + status(status) { this.status(status); return this; } - + notFound(){ return this.status(404).send(); } - + methodNotAllowed() { return this.status(405).send(); } - + ok() { return this.status(200).send(); } - + + setHeader(key, value) { + this.headers[key] = value; + return this; + } + json(data) { + this.setHeader('Content-Type', 'application/json'); this.body = JSON.stringify(data); return this; } -} \ No newline at end of file +}