Web framework.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. var http = require("http");
  2. var urllib = require("url");
  3. var fs = require("fs");
  4. var res404 = "404 not found: {{method}} {{pathname}}";
  5. var res403 = "403 forbidden: {{method}} {{pathname}}";
  6. function template(tpml, args) {
  7. for (var i in args) {
  8. tpml = tpml.split("{{"+i+"}}").join(args[i]);
  9. }
  10. return tpml;
  11. }
  12. function resJson(obj) {
  13. this.writeHead(200, {
  14. "content-type": "application/json"
  15. });
  16. this.end(JSON.stringify(obj));
  17. }
  18. function methodsMatch(route, req) {
  19. if (route.method === "ALL")
  20. return true;
  21. if (route.method === "GET" && req.method === "HEAD")
  22. return true;
  23. return route.method === req.method;
  24. }
  25. class App {
  26. constructor(options) {
  27. options = options || {};
  28. // 403 and 404 response
  29. this.res404 = options.res404 || res404;
  30. this.res403 = options.res403 || res403;
  31. // Script to be served as /webframe.js
  32. this.clientScript = "";
  33. // Create server
  34. if (options.server !== undefined) {
  35. this.server = options.server;
  36. } else {
  37. this.server = http.createServer();
  38. var port = options.port || process.env.PORT | 8080;
  39. var host = options.host || "127.0.0.1";
  40. this.server.listen(port, host);
  41. this.info("Listening on "+host+":"+port);
  42. }
  43. this._routeMap = {};
  44. this._routes = [];
  45. // Add scripts
  46. if (options.client_utils) {
  47. this.addScript("client_utils",
  48. fs.readFileSync(__dirname+"/client/utils.js", "utf8"));
  49. }
  50. // Serve /webframe.js
  51. this.get("/webframe.js", (req, res) => {
  52. res.writeHead(200, {
  53. "Content-Type": "application/javascript"
  54. });
  55. res.end(this.clientScript);
  56. });
  57. // Listen for requests
  58. this.server.on("request", (req, res) => {
  59. res.json = resJson;
  60. var url = urllib.parse(req.url);
  61. req.urlobj = url;
  62. var route = null;
  63. // With HEAD requests, we don't want to write anything
  64. if (req.method === "HEAD") {
  65. res.write = function() {};
  66. var end = res.end;
  67. res.end = function() { end.call(res); }
  68. }
  69. // If the route is in the hash map, use that
  70. var r = this._routeMap[url.pathname];
  71. if (r && (methodsMatch(r, req))) {
  72. route = r;
  73. // Search through the routes list and look for matching routes
  74. } else {
  75. for (var i in this._routes) {
  76. var r = this._routes[i];
  77. if (!methodsMatch(r, req))
  78. continue;
  79. if (r.pattern.test(req.urlobj.pathname)) {
  80. route = r;
  81. break;
  82. }
  83. }
  84. }
  85. // If we still have no route, 404
  86. if (route === null) {
  87. res.writeHead(404);
  88. res.end(template(this.res404,
  89. { method: req.method, pathname: req.urlobj.pathname }));
  90. return;
  91. }
  92. // Run all the middleware stuff if applicable
  93. var self = this;
  94. if (route.middleware) {
  95. var cbs = route.middleware.length;
  96. function cb() {
  97. if (--cbs === 0)
  98. route.func(req, res, self);
  99. }
  100. for (var i in route.middleware) {
  101. route.middleware[i](req, res, cb);
  102. }
  103. // Just run the function if there's no middleware
  104. } else {
  105. route.func(req, res, this);
  106. }
  107. });
  108. }
  109. /*
  110. * Add route.
  111. * Args:
  112. * method: "GET", "POST", "PUT", "DELETE", "ALL"
  113. * path: path,
  114. * func: function
  115. */
  116. route(method, path, middleware, func) {
  117. if (method !== "GET" && method !== "POST" && method !== "PUT" &&
  118. method !== "DELETE" && method !== "ALL") {
  119. throw new Error("Invalid method.");
  120. }
  121. // Before is optional
  122. if (func === undefined) {
  123. func = middleware;
  124. middleware = undefined;
  125. }
  126. // All necessary arguments must exist
  127. if (typeof path !== "string")
  128. throw new TypeError("Path must be a string.");
  129. if (typeof func !== "function")
  130. throw new TypeError("Func must be a function.");
  131. // All middlewares must exist
  132. if (middleware) {
  133. for (var i in middleware) {
  134. if (typeof middleware[i] !== "function") {
  135. this.panic(
  136. "Middleware "+i+" for "+method+" "+path+
  137. " is "+(typeof middleware[i])+", expected function.");
  138. return;
  139. }
  140. }
  141. }
  142. // Add to routes array or route map
  143. if (path[0] === "^") {
  144. var pat = new RegExp(path);
  145. this._routes.push({
  146. method: method,
  147. func: func,
  148. pattern: pat,
  149. middleware: middleware
  150. });
  151. } else {
  152. this._routeMap[path] = {
  153. method: method,
  154. func: func,
  155. middleware: middleware
  156. };
  157. }
  158. }
  159. /*
  160. * Add code to be served as /webframe.js
  161. */
  162. addScript(name, str) {
  163. var start = "(function "+name+"() {\n";
  164. var end = "\n})();\n"
  165. str = str.trim();
  166. this.clientScript += start + str + end;
  167. }
  168. /*
  169. * Template string
  170. */
  171. template(tmpl, args) { return template(tmpl, args); }
  172. get(path, middleware, func) { this.route("GET", path, middleware, func); }
  173. post(path, middleware, func) { this.route("POST", path, middleware, func); }
  174. put(path, middleware, func) { this.route("PUT", path, middleware, func); }
  175. delete(path, middleware, func) { this.route("DELETE", path, middleware, func); }
  176. all(path, middleware, func) { this.route("ALL", path, middleware, func); }
  177. info(str) {
  178. console.log("Info: "+str);
  179. }
  180. notice(str) {
  181. console.log("Notice: "+str);
  182. }
  183. warning(str) {
  184. console.log("Warning: "+str);
  185. }
  186. panic(str) {
  187. console.log("PANIC: "+str);
  188. process.exit(1);
  189. }
  190. }
  191. exports.static = require("./js/static");
  192. exports.middleware = require("./js/middleware");;
  193. exports.App = App;