Updated ES6 example.

Do some bugfixes
Added eslint global var for react gg ez
This commit is contained in:
Michael Bykovski 2017-07-25 18:48:07 +02:00
parent 91eef91b6b
commit a6fe285656
2 changed files with 32 additions and 22 deletions

View File

@ -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();
}
}
}

View File

@ -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;
}
}
}