Skip to content

Commit

Permalink
Removing each() & changing calls to for...of
Browse files Browse the repository at this point in the history
  • Loading branch information
avoidwork committed Jan 1, 2020
1 parent 4bfbf6b commit 771d8d5
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 81 deletions.
53 changes: 35 additions & 18 deletions lib/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const path = require("path"),
retsu = require("retsu"),
coerce = require("tiny-coerce"),
mime = require(path.join(__dirname, "mime.js")),
{canGet, each, hasBody, jsonWrap} = require(path.join(__dirname, "shared.js")),
{hasBody} = require(path.join(__dirname, "shared.js")),
regex = require(path.join(__dirname, "regex.js")),
rateHeaders = [
"x-ratelimit-limit",
Expand All @@ -23,6 +23,28 @@ function bypass (req, res, next) {
next();
}

function canGet (arg) {
return arg.includes("GET") || arg.includes("HEAD") || arg.includes("OPTIONS");
}

function jsonWrap (arg) {
const a = arg[0],
b = arg[arg.length - 1];

return (a === "\"" && b === "\"") || (a === "[" && b === "]") || (a === "{" && b === "}"); // eslint-disable-line no-extra-parens
}

function filecb (err, lstats, npath, nth, count, handled, req, res, next) {
if (err === null && handled === false) {
handled = true;
req.file = {path: npath, stats: lstats};
req.server.log("Routed request to disk", "debug");
next();
} else if (++count === nth && handled === false) {
res.error(404);
}
}

function file (req, res, next) {
if (req.headers.expect !== void 0) {
res.error(417);
Expand All @@ -44,20 +66,11 @@ function file (req, res, next) {
handled = false;

if (nth > 0) {
each(req.server.config.index, i => {
for (const i of req.server.config.index) {
const npath = path.join(lpath, i);

fs.stat(npath, (err, lstats) => {
if (err === null && handled === false) {
handled = true;
req.file = {path: npath, stats: lstats};
req.server.log("Routed request to disk", "debug");
next();
} else if (++count === nth && handled === false) {
res.error(404);
}
});
});
fs.stat(npath, (err, lstats) => filecb(err, lstats, npath, nth, count, handled, req, res, next));
}
} else {
next();
}
Expand Down Expand Up @@ -87,9 +100,10 @@ function parse (req, res, next) {
const args = req.body ? retsu.chunk(req.body.split(regex.bodySplit), 2) : [];

req.body = {};
each(args, i => {

for (const i of args) {
req.body[i[0]] = coerce(decodeURIComponent(i[1]));
});
}
} else if (type.includes("application/json") || jsonWrap(req.body)) {
try {
req.body = JSON.parse(req.body);
Expand Down Expand Up @@ -152,7 +166,10 @@ function rate (req, res, next) {
good = results.shift();

if (good) {
each(rateHeaders, (i, idx) => res.header(i, results[idx]));
for (const [idx, i] of rateHeaders.entries()) {
res.header(i, results[idx]);
}

next();
} else {
res.header("retry-after", config.reset);
Expand Down Expand Up @@ -187,9 +204,9 @@ function stream (req, res) {

// Setting the partial content headers
if (req.headers.range !== void 0) {
each(req.headers.range.replace(/^.*=/, "").split(",")[0].split("-"), (i, idx) => {
for (const [idx, i] of req.headers.range.replace(/^.*=/, "").split(",")[0].split("-")) {
options[idx === 0 ? "start" : "end"] = i ? parseInt(i, 10) : void 0;
});
}

// Byte offsets
if (isNaN(options.start) && isNaN(options.end) === false) {
Expand Down
31 changes: 1 addition & 30 deletions lib/shared.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,9 @@
"use strict";

function each (arr, fn) {
let i = -1;

for (const item of arr) {
fn(item, ++i);
}

return arr;
}

function hasBody (arg) {
return arg.includes("PATCH") || arg.includes("POST") || arg.includes("PUT");
}

function canGet (arg) {
return arg.includes("GET") || arg.includes("HEAD") || arg.includes("OPTIONS");
}

function canModify (arg) {
return arg.includes("DELETE") || hasBody(arg);
}

function jsonWrap (arg) {
const a = arg[0],
b = arg[arg.length - 1];

return (a === "\"" && b === "\"") || (a === "[" && b === "]") || (a === "{" && b === "}"); // eslint-disable-line no-extra-parens
}

module.exports = {
canGet,
canModify,
each,
hasBody,
jsonWrap
hasBody
};
8 changes: 6 additions & 2 deletions lib/tenso.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const path = require("path"),
dtrace = require(path.join(__dirname, "dtrace.js")),
middleware = require(path.join(__dirname, "middleware.js")),
regex = require(path.join(__dirname, "regex.js")),
{canModify} = require(path.join(__dirname, "shared.js")),
{hasBody} = require(path.join(__dirname, "shared.js")),
{hypermedia, ms, serialize} = require(path.join(__dirname, "utility.js")),
renderers = require(path.join(__dirname, "renderers.js")),
serializers = require(path.join(__dirname, "serializers.js")),
Expand Down Expand Up @@ -224,6 +224,10 @@ class Tenso extends Base {
return result;
}

canModify (arg) {
return arg.includes("DELETE") || hasBody(arg);
}

clf (req, res) {
return this.config.logging.format.replace("%v", req.headers.host)
.replace("%h", req.ip || "-")
Expand Down Expand Up @@ -320,7 +324,7 @@ class Tenso extends Base {
res.header("cache-control", `private${lcache.length > 0 ? ", " : ""}${lcache || ""}`);
}

if (canModify(req.method) === false && canModify(req.allow) && this.config.security.csrf === true && this.config.security.key in res.locals) {
if (this.canModify(req.method) === false && this.canModify(req.allow) && this.config.security.csrf === true && this.config.security.key in res.locals) {
res.header(this.config.security.key, res.locals[this.config.security.key]);
csrf = true;
}
Expand Down
57 changes: 26 additions & 31 deletions lib/utility.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ const path = require("path"),
uuid = require("tiny-uuid4"),
woodland = require("woodland"),
etag = require("tiny-etag"),
{each} = require(path.join(__dirname, "shared.js")),
middleware = require(path.join(__dirname, "middleware.js")),
regex = require(path.join(__dirname, "regex.js")),
serializers = require(path.join(__dirname, "serializers.js")),
Expand Down Expand Up @@ -83,17 +82,17 @@ function auth (obj, config) {

obj.router.blacklist(middleware.asyncFlag);

each(groups, k => {
for (const k of groups) {
config.auth[k] = (config.auth[k] || []).map(i => new RegExp(`^${i !== config.auth.uri.login ? i.replace(/\.\*/g, "*").replace(/\*/g, ".*") : ""}(\/|$)`, "i"));
});
}

each(Object.keys(config.auth), i => {
for (const i of Object.keys(config.auth)) {
if (config.auth[i].enabled) {
authMap[`${i}_uri`] = `/auth/${i}`;
authUris.push(`/auth/${i}`);
config.auth.protect.push(new RegExp(`^/auth/${i}(\/|$)`));
}
});
}

if (config.auth.local.enabled) {
authUris.push(config.auth.uri.redirect);
Expand Down Expand Up @@ -181,13 +180,13 @@ function auth (obj, config) {
}
};

each(config.auth.basic.list || [], i => {
for (const i of config.auth.basic.list || []) {
let args = i.split(":");

if (args.length > 0) {
x[args[0]] = {password: args[1]};
}
});
}

passport.use(new BasicStrategy((username, password, done) => {
delay(() => {
Expand Down Expand Up @@ -251,11 +250,11 @@ function auth (obj, config) {
ignoreExpiration: config.auth.jwt.ignoreExpiration === true
};

each(["algorithms", "audience", "issuer"], i => {
for (const i of ["algorithms", "audience", "issuer"]) {
if (config.auth.jwt[i] !== void 0) {
opts[i] = config.auth.jwt[i];
}
});
}

passport.use(new JWTStrategy(opts, (token, done) => {
delay(() => {
Expand Down Expand Up @@ -361,9 +360,9 @@ function auth (obj, config) {

let r = `(?!${config.auth.uri.root}/(`;

each(authUris, i => {
for (const i of authUris) {
r += i.replace("_uri", "") + "|";
});
}

r = r.replace(/\|$/, "") + ")).*$";
obj.always(r, middleware.guard).blacklist(middleware.guard);
Expand Down Expand Up @@ -430,11 +429,11 @@ function bootstrap (obj) {
// Setting 'always' routes before authorization runs
const routes = obj.config.routes.always || {};

each(Object.keys(routes), i => {
for (const i of Object.keys(routes)) {
if (typeof routes[i] === "function") {
obj.always(i, routes[i]).blacklist(routes[i]);
}
});
}

delete obj.config.routes.always;

Expand All @@ -448,17 +447,17 @@ function bootstrap (obj) {
}

// Setting routes
each(Object.keys(obj.config.routes), method => {
for (const method of Object.keys(obj.config.routes)) {
const lroutes = obj.config.routes[method];

each(Object.keys(lroutes), i => {
for (const i of Object.keys(lroutes)) {
if (typeof lroutes[i] === "function") {
obj[method](i, lroutes[i]);
} else {
obj[method](i, (req, res) => res.send(lroutes[i]));
}
});
});
}
}

return obj;
}
Expand Down Expand Up @@ -489,7 +488,7 @@ function hypermedia (req, res, rep) {
if (keys.length === 0) {
result = null;
} else {
each(keys, i => {
for (const i of keys) {
if (obj[i] !== void 0 && obj[i] !== null) {
const lid = id(i);
let lcollection, uri;
Expand Down Expand Up @@ -519,7 +518,7 @@ function hypermedia (req, res, rep) {
}
}
}
});
}

result = obj;
}
Expand Down Expand Up @@ -589,7 +588,7 @@ function hypermedia (req, res, rep) {
}

if (req.hypermedia) {
each(rep.data, i => {
for (const i of rep.data) {
if (i instanceof Object) {
marshal(i, "item", req.parsed.pathname.replace(regex.trailingSlash, ""));
} else {
Expand All @@ -603,7 +602,7 @@ function hypermedia (req, res, rep) {
}
}
}
});
}
}
} else if (rep.data instanceof Object && req.hypermedia) {
parent = req.parsed.pathname.split("/").filter(i => i !== "");
Expand All @@ -618,12 +617,12 @@ function hypermedia (req, res, rep) {

if (links.length > 0) {
if (headers.link !== void 0) {
each(headers.link.split('" <'), i => {
for (const i of headers.link.split('" <')) {
links.push({
uri: i.replace(/(^\<|\>.*$)/g, ""),
rel: i.replace(/(^.*rel\=\"|\"$)/g, "")
});
});
}
}

headers.link = keysort(links, "rel, uri").map(i => `<${i.uri}>; rel="${i.rel}"`).join(", ");
Expand Down Expand Up @@ -666,17 +665,14 @@ function serialize (req, res, arg) {
errz = arg instanceof Error,
result, serializer;

each(accepts, i => {
let mimetype = i.replace(regex.mimetype, ""),
output;
for (const i of accepts) {
let mimetype = i.replace(regex.mimetype, "");

if (serializers.has(mimetype)) {
output = false;
format = mimetype;
break;
}

return output;
});
}

serializer = serializers.get(format);

Expand All @@ -698,7 +694,6 @@ module.exports = {
bootstrap,
capitalize,
clone,
each,
explode,
hypermedia,
ms,
Expand Down

0 comments on commit 771d8d5

Please sign in to comment.