Skip to content

Commit

Permalink
refactor: add convenience methods to the framework http component and…
Browse files Browse the repository at this point in the history
… refactor the url lib methods

Add convenience methods 'buildQueryString' and 'getClientInfo' to the framework http component.
  • Loading branch information
simplymichael committed Jun 26, 2024
1 parent 22ba496 commit 6fd0a1b
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 5 deletions.
2 changes: 2 additions & 0 deletions src/framework/component/http/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use strict";

const methods = require("./methods");
const StatusCodes = require("./status-codes");
const StatusTexts = require("./status-texts").statusTexts;

Expand All @@ -8,4 +9,5 @@ module.exports = {
STATUS_CODES: Object.assign(Object.create(null), StatusCodes),
STATUS_TEXTS: Object.assign(Object.create(null), StatusTexts),
//CacheControlDirectives: require("./cache-control-directives").HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES,
...methods,
};
31 changes: 31 additions & 0 deletions src/framework/component/http/methods.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
module.exports = {
buildQueryString,
getClientInfo,
};

function buildQueryString(obj) {
const strBuilder = [];

if(typeof obj !== "object" || !obj) {
return "";
}

if(typeof obj === "string" || typeof obj === "number") {
return obj;
}

for (const [prop, value] of Object.entries(obj)) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
strBuilder.push(encodeURIComponent(prop) + "=" + encodeURIComponent(value));
}
}

return strBuilder.join("&");
}

function getClientInfo(req) {
return {
ipAddress: req.ip,
userAgent: req.headers["user-agent"],
};
};
16 changes: 11 additions & 5 deletions src/framework/lib/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,23 @@ function getValidUrl(baseUrl, path, apiBasePath) {
path = normalizeUrlPath(path) || "";
apiBasePath = normalizeUrlPath(apiBasePath) || "";

return baseUrl + (apiBasePath ? `/${apiBasePath}` : "") + `/${path}`;
let url = baseUrl;

if(apiBasePath) {
url += `/${apiBasePath}`;
}

url += `/${path}`;

return url;
}

function normalizeUrlPath(path) {
path = String(path);

if(path.startsWith("/")) {
if(path?.startsWith("/")) {
path = stripFirstNCharsFromString(path, 1);
}

if(path.endsWith("/")) {
if(path?.endsWith("/")) {
path = stripLastNCharsFromString(path, 1);
}

Expand Down

0 comments on commit 6fd0a1b

Please sign in to comment.