slower 1.1.19 → 1.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/router.js CHANGED
@@ -1,7 +1,7 @@
1
1
  const http = require('http');
2
2
  const https = require('https');
3
3
  const fs = require('fs');
4
- const { clone, noop, slugify, isSparseEqual, last, renderDynamicHTML, setSocketLocals, setSocketSecurityHeaders } = require('./utils');
4
+ const { clone, noop, slugify, isSparseEqual, last, renderDynamicHTML, setSocketLocals, setSocketSecurityHeaders, setResponseAssessors } = require('./utils');
5
5
  const mimetable = require('./mimetable.json');
6
6
 
7
7
  class Route {
@@ -43,7 +43,6 @@ class SlowerRouter {
43
43
  this.fallback = noop;
44
44
  this.allowedMethods = clone(SlowerRouter.http_methods);
45
45
  this.blockedMethodCallback = noop;
46
- this.mime_table = SlowerRouter.mime_table;
47
46
  this.tls = { use: false, key: null, cert: null };
48
47
  }
49
48
 
@@ -281,8 +280,9 @@ class SlowerRouter {
281
280
  * app.setAllowedMethods(['GET', 'POST']);
282
281
  */
283
282
  setAllowedMethods = function (methods = []) {
283
+ this.allowedMethods = [];
284
284
  // If not specified, all methods are allowed
285
- if (methods.length == 0 || methods == '*') {
285
+ if (methods.length == 0 || methods == '*') {
286
286
  return this.allowedMethods = JSON.parse(JSON.stringify(SlowerRouter.http_methods));
287
287
  }
288
288
  for (let i = 0; i < methods.length; i++) {
@@ -297,6 +297,67 @@ class SlowerRouter {
297
297
  return this;
298
298
  }
299
299
 
300
+ /*
301
+ Route Objects looks like:
302
+
303
+ {
304
+ type: "route",
305
+ path: "/",
306
+ method: "GET",
307
+ handle: someFunction
308
+ }
309
+
310
+ {
311
+ type: "middleware",
312
+ handle: someFunction
313
+ }
314
+
315
+ {
316
+ type: "fallback",
317
+ handle: someFunction
318
+ }
319
+
320
+ {
321
+ type: "static",
322
+ path: "/style.css",
323
+ file: "./www/assets/style.css"
324
+ }
325
+
326
+ {
327
+ type: "dynamic",
328
+ path: "/client.html",
329
+ file: "./www/templates/client.html",
330
+ data: {
331
+ "CLIENTID": someRenderingFunction
332
+ }
333
+ }
334
+
335
+ {
336
+ type: "fallbackfile",
337
+ file: "./www/pages/404.html"
338
+ data: {
339
+ "CUSTOM_ERROR_MESSAGE": () => { return err.message },
340
+ "CUSTOM_ERROR_CODE": someErrorCodeFetchingFunction
341
+ }
342
+ }
343
+
344
+ */
345
+ // Converts a series of objectRoutes into actual internal routes
346
+ parse = function (routeObjectList) {
347
+ for (let entry of routeObjectList) {
348
+ const { type, path, method, file, data, handle } = entry;
349
+ switch (type) {
350
+ case 'route': this.setRoute(path, method, handle); break;
351
+ case 'middleware': this.setMiddleware(handle); break;
352
+ case 'fallback': this.setFallback(handle); break;
353
+ case 'static': this.setStatic(path, file, undefined); break;
354
+ case 'dynamic': this.setDynamic(path, file, undefined, data); break;
355
+ case 'fallbackfile': this.setFallbackFile(file, undefined, data); break;
356
+ }
357
+ }
358
+ return this;
359
+ }
360
+
300
361
  // Starts the server - listening at <host>:<port>
301
362
  /**
302
363
  * @category Router
@@ -325,15 +386,18 @@ class SlowerRouter {
325
386
  try {
326
387
  // Sets local req.session object
327
388
  setSocketLocals(req);
389
+ setResponseAssessors(res);
328
390
  // Sets security headers in req.headers
329
391
  // This is set before custom callbacks are applies
330
392
  // so it is possible to override all of the headers
331
393
  if (!!this.strictHeaders) setSocketSecurityHeaders(req);
332
394
  // Runs all middlewares
333
- for (let i = 0; i < middle.length; i++) { middle[i](req, res); }
395
+ for (let i = 0; i < middle.length; i++) {
396
+ middle[i](req, res);
397
+ if (res.writableEnded) return; // if res.end() is caller early in a middleware
398
+ }
334
399
  // Only respond to allowed methods with callbacks, else, use the default empty response.
335
- if (
336
- allowedMethods.includes(req.method)) {
400
+ if (allowedMethods.includes(req.method)) {
337
401
  for (let i = 0; i < routes.length; i++) {
338
402
  let route = routes[i];
339
403
  if (
@@ -345,12 +409,16 @@ class SlowerRouter {
345
409
  ) {
346
410
  i = routes.length;
347
411
  route.callback(req, res);
412
+ if (res.writableEnded) return; // if res.end() was called
413
+ else res.end(); // if res.end() was not called
348
414
  return;
349
415
  }
350
416
  }
351
417
  fallback(req,res);
418
+ if (!res.writableEnded) res.end(); // No need to call res.end() on handlers anymore
352
419
  } else {
353
420
  blockedMethodCallback(req, res);
421
+ if (!res.writableEnded) res.end(); // No need to call res.end() on handlers anymore
354
422
  }
355
423
  } catch(err) {
356
424
  console.log(err);
package/lib/utils.js CHANGED
@@ -69,21 +69,32 @@ const renderDynamicHTML = (html, patterns) => {
69
69
  return template;
70
70
  }
71
71
 
72
- const setSocketLocals = (socket) => {
73
- socket.session = {};
74
- socket.session.port = socket.socket.localPort;
75
- socket.session.rport = socket.socket.remotePort;
76
- socket.session.host = (
77
- socket.socket.localAddress.startsWith('::') ?
78
- socket.socket.localAddress.substring(
79
- socket.socket.localAddress.indexOf(':',2)+1
80
- ) : socket.socket.localAddress);
81
- socket.session.rhost = (
82
- socket.socket.remoteAddress.startsWith('::') ?
83
- socket.socket.remoteAddress.substring(
84
- socket.socket.remoteAddress.indexOf(':',2)+1
85
- ) : socket.socket.remoteAddress);
86
- return socket;
72
+ const setSocketLocals = (reqSocket) => {
73
+ reqSocket.session = {};
74
+ reqSocket.session.port = reqSocket.socket.localPort;
75
+ reqSocket.session.rport = reqSocket.socket.remotePort;
76
+ reqSocket.session.host = (
77
+ reqSocket.socket.localAddress.startsWith('::') ?
78
+ reqSocket.socket.localAddress.substring(
79
+ reqSocket.socket.localAddress.indexOf(':',2)+1
80
+ ) : reqSocket.socket.localAddress);
81
+ reqSocket.session.rhost = (
82
+ reqSocket.socket.remoteAddress.startsWith('::') ?
83
+ reqSocket.socket.remoteAddress.substring(
84
+ reqSocket.socket.remoteAddress.indexOf(':',2)+1
85
+ ) : reqSocket.socket.remoteAddress);
86
+ return reqSocket;
87
+ }
88
+
89
+ const setResponseAssessors = (resSocket) => {
90
+ resSocket.sendText = (data, code = 200) => {
91
+ resSocket.writeHead(code, { 'Content-Type': 'text/plain' });
92
+ resSocket.write(data);
93
+ };
94
+ resSocket.sendJSON = (data, code = 200) => {
95
+ resSocket.writeHead(code, { 'Content-Type': 'application/json' });
96
+ resSocket.write(data);
97
+ };
87
98
  }
88
99
 
89
100
  const setSocketSecurityHeaders = (req) => {
@@ -143,4 +154,4 @@ const toBool = [() => true, () => false];
143
154
 
144
155
  const clone = (object) => JSON.parse(JSON.stringify(object));
145
156
 
146
- module.exports = { clone, noop, slugify, isSparseEqual, toBool, last, renderDynamicHTML, setSocketLocals, setSocketSecurityHeaders };
157
+ module.exports = { clone, noop, slugify, isSparseEqual, toBool, last, renderDynamicHTML, setSocketLocals, setSocketSecurityHeaders, setResponseAssessors };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slower",
3
- "version": "1.1.19",
3
+ "version": "1.1.20",
4
4
  "description": "A package for simple HTTP server routing.",
5
5
  "main": "index.js",
6
6
  "directories": {
package/readme.md CHANGED
@@ -170,7 +170,13 @@ a socket will receive the modified socket instead.
170
170
  <socket>.session.host: String => The local host interface address
171
171
  <socket>.session.rhost: String => The remote host interface address
172
172
  ```
173
- - It is possible to use the ```socket.session``` object to append data that will persist
173
+ - Only on 'response' ```net.Socket```:
174
+ ```
175
+ <socket>.sendText: Function (data, code) => A helper for responding with plaintext data. No need to declare writeHead() or end() if using this.
176
+ <socket>.sendJSON: Function (data, code) => A helper for responding with JSON data. No need to declare writeHead() or end() if using this.
177
+
178
+ ```
179
+ - It is possible to use the ```socket.session``` object to append data that will persist
174
180
  during the lifetime of a single connection. Useful for keeping short-life local variables.
175
181
 
176
182
  - In HTTP ```http.IncomingMessage``` instances, the 'socket' instance is found over 'request'.