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 4.7KB

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