From f966e0564ee2d179dfaa8db3f8a273f7be8d6ab9 Mon Sep 17 00:00:00 2001 From: buzz-lightsnack-2007 <73412182+buzz-lightsnack-2007@users.noreply.github.com> Date: Sun, 6 Apr 2025 14:09:48 +0800 Subject: [PATCH] reuse errors.JS and hash.JS from https://codeberg.org/buzzcode2007/FCC-Project-URLShortener/src/branch/main/scripts/utilities --- scripts/utilities/errors.JS | 25 ++++++++++++++++++++++++ scripts/utilities/hash.JS | 38 +++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 scripts/utilities/errors.JS create mode 100644 scripts/utilities/hash.JS diff --git a/scripts/utilities/errors.JS b/scripts/utilities/errors.JS new file mode 100644 index 0000000..a18275e --- /dev/null +++ b/scripts/utilities/errors.JS @@ -0,0 +1,25 @@ +class CustomErrors {} + +CustomErrors.URL = class URL_Error extends Error { + constructor(message, URL) { + super((message) ? message : `invalid url`); + this.name = "URL Problem"; + this.stack = URL; + }; +} + +CustomErrors.DBProblem = class DB_Error extends Error { + constructor(message) { + super(message); + this.name = "Database Problem" + } +} + +CustomErrors.HashProblem = class DB_Error extends Error { + constructor(message) { + super(message); + this.name = "Hash Problem" + } +} + +module.exports = CustomErrors \ No newline at end of file diff --git a/scripts/utilities/hash.JS b/scripts/utilities/hash.JS new file mode 100644 index 0000000..db025cb --- /dev/null +++ b/scripts/utilities/hash.JS @@ -0,0 +1,38 @@ +class Hash { + #data; + + constructor(DATA, METHOD) { + this.#data = DATA; + this.algorithm = (METHOD) ? METHOD : "SHA-512"; + this.arrayBuffer = crypto.subtle.digest(this.algorithm, (new TextEncoder()).encode(DATA)) + }; + + /* + Represent the hash in another format. + + @param {string} TYPE the output format + @return {object} the converted hash + */ + async convert(TYPE) { + if (TYPE) { + switch (TYPE) { + case `Uint8Array`: + this[TYPE] = new Uint8Array(await this.arrayBuffer); + break; + case `Array`: + this[TYPE] = Array.from(new Uint8Array(await this.arrayBuffer)); + break; + case `Number`: + this[TYPE] = parseInt((Array.from(new Uint8Array(await this.arrayBuffer))).join()); + break; + case `String`: + this[TYPE] = Array.from(new Uint8Array(await this.arrayBuffer)).join(``); + }; + + return(this[TYPE]) + } + } +} + + +module.exports = Hash; \ No newline at end of file