This commit is contained in:
Benjamin Toby
2024-12-15 12:27:16 +01:00
parent d9d32a4643
commit bc037e839f
314 changed files with 10191 additions and 408 deletions
@@ -1,60 +1,58 @@
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const http = require("http");
/**
* Parse request cookies
* ==============================================================================
* ===================================================
*
* @description This function takes in a request object and returns the cookies as a JS object
* @description This function takes in a request object and
* returns the cookies as a JS object
*
* @async
*
* @param {object} params - main params object
* @param {http.IncomingMessage} params.request - HTTPS request object
* @param {http.IncomingMessage & Object<string, any>} [params.request] - HTTPS request object
* @param {string} [params.cookieString]
*
* @returns {any | null}
* @returns {Object<string, string>}
*/
module.exports = function ({ request }) {
/**
* Check inputs
*
* @description Check inputs
*/
module.exports = function parseCookies({ request, cookieString }) {
try {
/** @type {string | undefined} */
const cookieStr = request
? request.headers.cookie
: cookieString
? cookieString
: undefined;
/** @type {string | undefined} */
const cookieString = request.headers.cookie;
if (!cookieStr) return {};
if (!cookieString || typeof cookieString !== "string") {
return null;
}
/** @type {string[]} */
const cookieSplitArray = cookieString.split(";");
/** @type {*} */
let cookieObject = {};
cookieSplitArray.forEach((keyValueString) => {
const [key, value] = keyValueString.split("=");
if (key && typeof key == "string") {
cookieObject[key.replace(/^ +| +$/, "")] =
value && typeof value == "string"
? value.replace(/^ +| +$/, "")
: null;
if (!cookieStr || typeof cookieStr !== "string") {
return {};
}
});
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
/** @type {string[]} */
const cookieSplitArray = cookieStr.split(";");
return cookieObject;
/** @type {Object<string, string>} */
let cookieObject = {};
cookieSplitArray.forEach((keyValueString) => {
const [key, value] = keyValueString.split("=");
if (key && typeof key == "string") {
const parsedKey = key.replace(/^ +| +$/, "");
cookieObject[parsedKey] =
value && typeof value == "string"
? value.replace(/^ +| +$/, "")
: "";
}
});
return cookieObject;
} catch (/** @type {any} */ error) {
console.log(`ERROR parsing cookies: ${error.message}`);
return {};
}
};
+26
View File
@@ -0,0 +1,26 @@
// @ts-check
/**
* # Get Number from any input
* @param {any} num input
* @param {number} [decimals] number of decimals to round to
* @returns {number} number or 0 in case of error
* @example
* numberfy("123") // 123
* numberfy("123.456") // 123
* numberfy("123.456", 2) // 123.46
* numberfy("123.456", 0) // 123
* numberfy("123.456", 3) // 123.456
*/
module.exports = function numberfy(num, decimals) {
try {
const numberfiedNum = Number(num);
if (typeof numberfiedNum !== "number") return 0;
if (isNaN(numberfiedNum)) return 0;
if (decimals) return Number(numberfiedNum.toFixed(decimals));
return Math.round(numberfiedNum);
} catch (/** @type {any} */ error) {
console.log(`Numberfy ERROR: ${error.message}`);
return 0;
}
};
@@ -0,0 +1,48 @@
// @ts-check
/**
*
* @param {object} params
* @param {import("../types").CookieObject[]} params.cookies
* @returns {string[]}
*/
function serializeCookies({ cookies }) {
/** @type {string[]} */
let cookiesStringsArray = [];
for (let i = 0; i < cookies.length; i++) {
const cookieObject = cookies[i];
let cookieString = `${cookieObject.name}=${cookieObject.value}`;
if (cookieObject.maxAge) {
cookieString += `;Max-Age=${cookieObject.maxAge}`;
}
if (cookieObject.path) {
cookieString += `;Path=${cookieObject.path}`;
}
if (cookieObject.domain) {
cookieString += `;Domain=${cookieObject.domain}`;
}
if (cookieObject.secure) {
cookieString += ";Secure";
}
if (cookieObject.httpOnly) {
cookieString += ";HttpOnly";
}
if (cookieObject.sameSite) {
cookieString += `;SameSite=${cookieObject.sameSite}`;
}
if (cookieObject.expires) {
cookieString += `;expires=${cookieObject.expires}`;
}
if (cookieObject.priority) {
cookieString += `;priority=${cookieObject.priority}`;
}
cookiesStringsArray.push(cookieString);
}
return cookiesStringsArray;
}
module.exports = serializeCookies;
@@ -0,0 +1,43 @@
// @ts-check
const EJSON = require("./ejson");
/** @type {import("../types").SerializeQueryFnType} */
function serializeQuery(query) {
let str = "?";
if (typeof query !== "object") {
console.log("Invalid Query type");
return str;
}
if (Array.isArray(query)) {
console.log("Query is an Array. This is invalid.");
return str;
}
if (!query) {
console.log("No Query provided.");
return str;
}
const keys = Object.keys(query);
/** @type {string[]} */
const queryArr = [];
keys.forEach((key) => {
if (!key || !query[key]) return;
const value = query[key];
if (typeof value === "object") {
const jsonStr = EJSON.stringify(value);
queryArr.push(`${key}=${encodeURIComponent(String(jsonStr))}`);
} else if (typeof value === "string" || typeof value === "number") {
queryArr.push(`${key}=${encodeURIComponent(value)}`);
}
});
str += queryArr.join("&");
return str;
}
module.exports = serializeQuery;
+27
View File
@@ -0,0 +1,27 @@
// @ts-check
/**
* # Return the slug of a string
* @param {string} str input
* @returns {string} slug or empty string in case of error
* @example
* slugify("Hello World") // "hello-world"
* slugify("Yes!") // "yes"
* slugify("Hello!!! World!") // "hello-world"
*/
module.exports = function slugify(str) {
try {
return String(str)
.trim()
.toLowerCase()
.replace(/ {2,}/g, " ")
.replace(/ /g, "-")
.replace(/[^a-z0-9]/g, "-")
.replace(/-{2,}/g, "-")
.replace(/^-/, "")
.replace(/-$/, "");
} catch (/** @type {any} */ error) {
console.log(`Slugify ERROR: ${error.message}`);
return "";
}
};