120d1fd686dd1b9a95a7ca7417ffe55358c1e7a5
[yaffs-website] / vendor / jcalderonzumba / gastonjs / src / Client / Server / server.js
1 Poltergeist.Server = (function () {
2
3   /**
4    * Server constructor
5    * @param owner
6    * @param port
7    * @constructor
8    */
9   function Server(owner, port) {
10     this.server = require('webserver').create();
11     this.port = port;
12     this.owner = owner;
13     this.webServer = null;
14   }
15
16   /**
17    * Starts the web server
18    */
19   Server.prototype.start = function () {
20     var self = this;
21     this.webServer = this.server.listen(this.port, function (request, response) {
22       self.handleRequest(request, response);
23     });
24   };
25
26   /**
27    * Send error back with code and message
28    * @param response
29    * @param code
30    * @param message
31    * @return {boolean}
32    */
33   Server.prototype.sendError = function (response, code, message) {
34     response.statusCode = code;
35     response.setHeader('Content-Type', 'application/json');
36     response.write(JSON.stringify(message, null, 4));
37     response.close();
38     return true;
39   };
40
41
42   /**
43    * Send response back to the client
44    * @param response
45    * @param data
46    * @return {boolean}
47    */
48   Server.prototype.send = function (response, data) {
49     console.log("RESPONSE: " + JSON.stringify(data, null, 4).substr(0, 200));
50
51     response.statusCode = 200;
52     response.setHeader('Content-Type', 'application/json');
53     response.write(JSON.stringify(data, null, 4));
54     response.close();
55     return true;
56   };
57
58   /**
59    * Handles a request to the server
60    * @param request
61    * @param response
62    * @return {boolean}
63    */
64   Server.prototype.handleRequest = function (request, response) {
65     var commandData;
66     if (request.method !== "POST") {
67       return this.sendError(response, 405, "Only POST method is allowed in the service");
68     }
69     console.log("REQUEST: " + request.post + "\n");
70     try {
71       commandData = JSON.parse(request.post);
72     } catch (parseError) {
73       return this.sendError(response, 400, "JSON data invalid error: " + parseError.message);
74     }
75
76     return this.owner.serverRunCommand(commandData, response);
77   };
78
79   return Server;
80 })();