superjson-db
Advanced tools
+235
-254
@@ -1,266 +0,247 @@ | ||
| const fs = require('fs'); | ||
| let config = fs.readFileSync(`${__dirname}/config.json`); config = JSON.parse(config); | ||
| module.exports = class WastefulDB { | ||
| /** | ||
| * @param {Boolean} options.feedback Provides confirmation via the console each time most of the functions successfully execute. (default: true) | ||
| * @param {String} options.path Provide a custom directory/path to read/write each JSON file. Ignoring this will automatically read/write to ".../wastefuldb/data/" | ||
| * @param {Boolean} options.serial When true, you are no longer required to include an id variable to your file data. Instead, the identifier is based on the directory size at the time. (default: true) | ||
| */ | ||
| constructor(options = {feedback, path, serial}) { | ||
| this.feedback = options.feedback || config.feed; | ||
| this.path = options.path || `${__dirname}/data/`; | ||
| this.serial = options.serial || config.serial; | ||
| const { error } = require("console"); | ||
| const fs = require("fs"); | ||
| const req = (parm) => { | ||
| if (parm == " " || parm == "" || parm == " " || parm == undefined) { | ||
| throw new Error("parameter required") | ||
| } else { | ||
| return; | ||
| } | ||
| /** | ||
| * Create a JSON file containing organized and modifiable information to be retrieved later. | ||
| * @param {Object} data Content to be stringified and stored in JSON. | ||
| * @param {String} data.id File name & identifier (REQUIRED) | ||
| */ | ||
| insert(data) { | ||
| if(!(data instanceof Object)) return console.log("Information given must be an Object."); | ||
| try { | ||
| let obj, altid=false, dirsize = fs.readdirSync(this.path); dirsize = dirsize.length; | ||
| if(this.serial == true) { | ||
| (data.id > 0) ? data._id = dirsize : data.id = dirsize; data.id ? altid=true : altid; | ||
| console.log(data); | ||
| obj = [ data ]; obj = JSON.stringify(obj); | ||
| fs.writeFileSync(`${this.path}${data._id || data.id}.json`, obj); | ||
| this.feedback == true ? console.log(`Successfully created 1 document. ( ${data._id || data.id}.json )`) : ""; | ||
| } else { | ||
| if(!data.id) return console.log("Cannot create document without valid 'id' variable."); | ||
| obj = [data] | ||
| obj = JSON.stringify(obj); | ||
| fs.writeFileSync(`${this.path}${data.id}.json`, obj); | ||
| this.feedback == true ? console.log("Successfully created 1 document.") : ""; | ||
| } | ||
| } | ||
| catch(err) { | ||
| console.log("Error: " + err.message); | ||
| } | ||
| } | ||
| const checkObj = (parm) => { | ||
| if (typeof (parm) !== "object") { | ||
| throw new Error("The parameter should be object"); | ||
| } else { | ||
| return; | ||
| } | ||
| /** | ||
| * Retrieves and parses the data within the specified file. | ||
| * @param {Object | String} [data] The identifier of a file. | ||
| * @returns {Array} | ||
| */ | ||
| find(data) { | ||
| try { | ||
| let info = fs.readFileSync(`${this.path}${data.id || data}.json`); | ||
| info = JSON.parse(info); | ||
| this.feedback == true ? console.log("Successfully found 1 document.") : ""; | ||
| return info[0]; | ||
| } catch(err) { | ||
| console.log("Error: " + err.message); | ||
| } | ||
| } | ||
| const checkStr = (parm) => { | ||
| if (typeof (parm) !== "string") { | ||
| throw new Error("The parameter should be a string"); | ||
| } else { | ||
| return; | ||
| } | ||
| } | ||
| const checkBol = (parm) => { | ||
| if (typeof (parm) !== "boolean" || typeof (parm) !== "string") { | ||
| throw new Error("The parameter should be a string or a boolean"); | ||
| } else { | ||
| return; | ||
| } | ||
| } | ||
| const read = (dbname = "") => { | ||
| req(dbname) | ||
| let data = fs.readFileSync(sdp().folder + dbname + ".json", { encoding: "utf8" }); | ||
| return data; | ||
| } | ||
| const write = (dbname, data) => { | ||
| req(dbname); | ||
| req(data); | ||
| fs.writeFileSync(sdp().folder + dbname + ".json", data); | ||
| } | ||
| const sdp = () => { | ||
| return { | ||
| folder: "./json-db/db/", | ||
| // to create new db after validation | ||
| newDb(dbname) { | ||
| req(dbname); | ||
| checkStr(dbname); | ||
| if (sdp().dbExist(dbname)) { | ||
| throw error("db already exist"); | ||
| } | ||
| else { | ||
| let fname = dbname + ".json"; | ||
| let c = fs.createWriteStream(sdp().folder + fname); | ||
| c.write("{}") | ||
| } | ||
| }, | ||
| // read all db files and validate | ||
| getFiles(dir = sdp().folder, files_) { | ||
| files_ = files_ || []; | ||
| var files = fs.readdirSync(dir); | ||
| for (var i in files) { | ||
| var name = dir + '/' + files[i]; | ||
| if (fs.statSync(name).isDirectory()) { | ||
| sdp().getFiles(name, files_); | ||
| } else { | ||
| let rep = files[i].replace(".json", "").trim(); | ||
| files_.push(rep); | ||
| } | ||
| } | ||
| return files_; | ||
| }, | ||
| put(object, dbname, ai) { | ||
| req(object); | ||
| req(dbname); | ||
| req(ai); | ||
| checkObj(object); | ||
| checkStr(dbname); | ||
| checkBol(ai); | ||
| if (ai !== true) { | ||
| if (sdp().keyExist(dbname, ai)) { | ||
| throw new Error("The Key already exist"); | ||
| /** | ||
| * Find and update a specified element within a file. Set "math" to be true for SIMPLE math. | ||
| * @type {Object} | ||
| * @param {Object} data Object containing arguments to successully update files. (id, element, change, math?) | ||
| * @param {String} data.id Identifier of the target file to update. | ||
| * @param {String} data.element The element OR parent element of a child element. | ||
| * @param {String} [data.child] The child of the specified element. | ||
| * @param {String} data.change Changes to be made to the target element. | ||
| * @param {Boolean} [data.math=false] Whether the change requires simple math or not. (Default: false) | ||
| * | ||
| * @param {Object} [element] Object containing arguments used to locate files based on file contents rather than an ID. | ||
| * @param {String} [element.name] The name of the field to search for and compare to the provided 'content'. | ||
| * @param {String} [element.content] The contents of the previously given field in order to find a specific file. | ||
| */ | ||
| update(data = {id, element, child, change, math:false}, element = {name:undefined, content:undefined}) { | ||
| /* | ||
| 'element' variable serves as an alternate method of locating files. | ||
| when using such, you are not required to include an id field in 'data'. | ||
| this is meant for cases in which serialization is set to 'true' - | ||
| in order to find and update files containing unique elements. | ||
| element.name == name of a field to find | ||
| element.content == the contents of the field to match | ||
| ex: | ||
| { | ||
| name: "pass", | ||
| content: "abc" | ||
| } | ||
| */ | ||
| let obj, files; | ||
| try { | ||
| if(data.element == undefined || data.change == undefined) return console.error("You must provide information needed to update files."); // if function is empty | ||
| if(element instanceof Object && element.name != undefined && element.content != undefined) { // run collect-type function for updates | ||
| if((element.name && !element.content) || (!element.name && element.content)) return console.error("Unable to locate file with missing field. ('name' or 'content')"); | ||
| files = fs.readdirSync(`${this.path}`); | ||
| files.forEach((file) => { | ||
| let target = fs.readFileSync(`${this.path}${file}`); | ||
| target = JSON.parse(target); target = target[0]; | ||
| if(target[element.name] && target[element.name] == element.content) { | ||
| if(data.math == true) { | ||
| if(data.child) { | ||
| if(isNaN(Number((target[data.element])[data.child]) || isNaN(Number(data.change)))) return console.error("Unable to update file due to given element, element child, or change returning NaN."); | ||
| (target[data.element])[data.child] = Number((target[data.element])[data.child]) + (Number(data.change)); | ||
| obj = [ target ]; obj = JSON.stringify(obj); | ||
| fs.writeFileSync(`${this.path}${file}`, obj); | ||
| } else { | ||
| if(isNaN(Number(target[data.element])) || isNaN(Number(data.change))) return console.error("Unable to update file due to given element or change returning NaN."); | ||
| target[data.element] = Number(target[data.element] + (Number(data.change))); | ||
| obj = [ target ]; obj = JSON.stringify(obj); | ||
| fs.writeFileSync(`${this.path}${file}`, obj); | ||
| } | ||
| } else { | ||
| if(data.child) { | ||
| (target[data.element])[data.child] = (data.change == "true" ? true : data.change == "false" ? false : data.change); | ||
| obj = [target]; obj = JSON.stringify(obj); | ||
| fs.writeFileSync(`${this.path}${file}`, obj); | ||
| } else { | ||
| target[data.element] = (data.change == "true" ? true : data.change == "false" ? false : data.change); | ||
| obj = [ target ]; obj = JSON.stringify(obj); | ||
| fs.writeFileSync(`${this.path}${file}`, obj); | ||
| } | ||
| } | ||
| this.feedback == true ? console.log(`Successfully updated 1 document. ( ${file} )`) : ""; | ||
| } | ||
| }) | ||
| } else { // run standard update function | ||
| if(data.id == undefined || data.element == undefined || data.change == undefined) return console.error("One or more fields is incomplete. ('id', 'element', and/or 'change')."); | ||
| let file = fs.readFileSync(`${this.path}${data.id}.json`); file = JSON.parse(file); file = file[0]; | ||
| if(file[data.element] == null || undefined) { // Insert new field if the provided element does not exist | ||
| file[data.element] = data.change; | ||
| obj = [ file ]; obj = JSON.stringify(obj); | ||
| fs.writeFileSync(`${this.path}${data.id}.json`, obj); | ||
| } else { // If element exists: | ||
| if(data.math == true) { // If math is set to true: | ||
| if(isNaN(Number(file[data.element])) || isNaN(Number(data.change))) return console.error("Unable to update file due to given element or change returning NaN."); | ||
| file[data.element] = Number(file[data.element] + (Number(data.change))); | ||
| obj = [ file ]; obj = JSON.stringify(obj); | ||
| fs.writeFileSync(`${this.path}${data.id}.json`, obj); | ||
| } else { // If math is set to false: | ||
| file[data.element] = (data.change == "true" ? true : data.change == "false" ? false : data.change); | ||
| obj = [ file ]; obj = JSON.stringify(obj); | ||
| fs.writeFileSync(`${this.path}${data.id}.json`, obj); | ||
| } | ||
| } | ||
| this.feedback == true ? console.log("Successfully updated 1 document.") : ""; | ||
| } | ||
| }catch(err){ | ||
| console.error("Error: " + err.message); | ||
| } | ||
| } | ||
| /** | ||
| * Reads each file within the directory, parses, pushes and returns an object of the information in each JSON file. Providing an id and/or element will filter through and push each file matching the profile. | ||
| * @param {Object} [data=undefined] | ||
| * @param {String} [data.id] | ||
| * @param {String} [data.element] | ||
| * @returns {Object} | ||
| */ | ||
| collect(data) { | ||
| let obj = [] | ||
| try { | ||
| if(!data) { | ||
| let files = fs.readdirSync(`${this.path}`); | ||
| files.forEach(file => { | ||
| let info = fs.readFileSync(`${this.path}${file}`); if(!obj) return new Error("File abnormality ocurred whilst attempting to read a file.\nFile name: " + file) | ||
| info = JSON.parse(info); info = info[0]; | ||
| obj.push(info); | ||
| } | ||
| if (sdp().dbExist(dbname) && ai === true) { | ||
| let r = read(dbname); | ||
| if (r == "{}") { | ||
| write(dbname, `{"0":${JSON.stringify(object)}}`) | ||
| return true; | ||
| } else { | ||
| let r = read(dbname); | ||
| let s = r.slice(1, -1); | ||
| let p = JSON.parse(r) | ||
| let oe = Object.entries(p); | ||
| let id = oe.pop()[0]; | ||
| if (parseInt(id) + 1 !== NaN) { | ||
| write(dbname, `{${s},"${parseInt(id) + 1}":${JSON.stringify(object)}}`) | ||
| return true; | ||
| } else { | ||
| write(dbname, `{${s},"0":${JSON.stringify(object)}}`) | ||
| return true; | ||
| } | ||
| } | ||
| } | ||
| if (sdp().dbExist(dbname) && ai !== true) { | ||
| let r = read(dbname); | ||
| if (r == "{}") { | ||
| write(dbname, `{"${ai}":${JSON.stringify(object)}}`) | ||
| return true; | ||
| } else { | ||
| if (!sdp().keyExist(dbname, ai)) { | ||
| let r = read(dbname); | ||
| let s = r.slice(1, -1); | ||
| write(dbname, `{${s},"${ai}":${JSON.stringify(object)}}`) | ||
| return true; | ||
| } else { | ||
| sdp().err("key already exists in db"); | ||
| return false; | ||
| } | ||
| } | ||
| } | ||
| }, | ||
| dbExist(dbname) { | ||
| req(dbname) | ||
| checkStr(dbname); | ||
| let files = sdp().getFiles(sdp().folder); | ||
| fileArray = []; | ||
| files.forEach(e => { | ||
| if (e === dbname) { | ||
| fileArray.push(e) | ||
| } | ||
| }); | ||
| return obj; | ||
| } else { | ||
| let files = fs.readdirSync(`${this.path}`); | ||
| files.forEach(file => { | ||
| let target = fs.readFileSync(`${this.path}${file}`); | ||
| if(!target) return console.error("Couldn't find any files pertaining to the given fields.") | ||
| target = JSON.parse(target); target = target[0]; | ||
| if(data.id && data.element == undefined) { // collect({id: }); | ||
| if(target.id == data.id) return obj.push(target); | ||
| } else if(data.element && data.id == undefined) { // collect() | ||
| if(target[data.element]) return obj.push(target); | ||
| } else if(data.element && data.id) { | ||
| if(target.id == data.id && target[data.element]) return obj.push(target); | ||
| } else { | ||
| return; | ||
| } | ||
| }); | ||
| } | ||
| } catch(err) { | ||
| console.log("Error: " + err.message); | ||
| } | ||
| } | ||
| if (fileArray.length == 0) { | ||
| return false; | ||
| } else { | ||
| return true; | ||
| } | ||
| }, | ||
| keyExist(dbname, key) { | ||
| req(dbname); | ||
| req(key); | ||
| checkStr(dbname); | ||
| checkStr(key); | ||
| if (sdp().dbExist(dbname)) { | ||
| let all = sdp().getAll(dbname); | ||
| let itm = []; | ||
| for (let item in all) { | ||
| if (item === key) { | ||
| itm.push(true) | ||
| } | ||
| } | ||
| if (itm[0]) { | ||
| return true; | ||
| } else { | ||
| return false; | ||
| } | ||
| } | ||
| }, | ||
| get(dbname, key) { | ||
| req(dbname); | ||
| req(key); | ||
| checkStr(dbname); | ||
| checkStr(key); | ||
| if (sdp().keyExist(dbname, key)) { | ||
| let rd = read(dbname); | ||
| return JSON.parse(rd)[key]; | ||
| } else { | ||
| throw new Error("db | key doesn't exist") | ||
| } | ||
| }, | ||
| getAll(dbname) { | ||
| req(dbname); | ||
| checkStr(dbname) | ||
| if (sdp().dbExist(dbname)) { | ||
| let rd = read(dbname); | ||
| return JSON.parse(rd); | ||
| } else { | ||
| throw new Error("db doesn't exist") | ||
| } | ||
| }, | ||
| deleteDb(dbname) { | ||
| req(dbname); | ||
| checkStr(dbname) | ||
| if (sdp().dbExist(dbname)) { | ||
| fs.unlinkSync(sdp().folder + dbname + ".json"); | ||
| return "db deleted succesfully"; | ||
| } else { | ||
| throw new Error("No db to delete") | ||
| } | ||
| }, | ||
| deleteAll(dbname) { | ||
| req(dbname); | ||
| checkStr(dbname); | ||
| if (sdp().dbExist(dbname)) { | ||
| write(dbname, "{}"); | ||
| return "all data has been deleted"; | ||
| } else { | ||
| throw new Error("No db to delete data") | ||
| } | ||
| }, | ||
| deleteKey(dbname, key) { | ||
| req(dbname); | ||
| req(key); | ||
| checkStr(dbname); | ||
| checkStr(key); | ||
| if (sdp().keyExist(dbname, key)) { | ||
| let data = read(dbname); | ||
| let parse = JSON.parse(data); | ||
| let obj = {}; | ||
| for (item in parse) { | ||
| if (item !== key) { | ||
| obj[item] = parse[item]; | ||
| } | ||
| } | ||
| let stfy = JSON.stringify(obj); | ||
| write(dbname, stfy); | ||
| return "Key has been deleted succesfully"; | ||
| /** | ||
| * Search the given directory for a specified identifier regardless of file name. | ||
| * @param {String} data Identifier to scan for in each file. | ||
| * @returns {Array} | ||
| */ | ||
| get(data, callback) { | ||
| try { | ||
| let files = fs.readdirSync(`${this.path}`) | ||
| files.forEach(file => { | ||
| let info = fs.readFileSync(`${this.path}${file}`) | ||
| let obj = JSON.parse(info); obj = obj[0]; | ||
| if(!obj) return new Error("File abnormality occurred whilst attempting to read.\nFile name: " + file); | ||
| if(obj.id == data.id || data) { | ||
| this.feedback == true ? console.log("Successfully retrieved 1 document.") : ""; | ||
| return callback(obj); | ||
| } | ||
| }) | ||
| }catch(err){ | ||
| console.log("Error: " + err.message); | ||
| } else { | ||
| throw new Error("Key doesn't exist") | ||
| } | ||
| }, | ||
| err(error) { | ||
| throw new Error(error); | ||
| }, | ||
| update(object, dbname, key) { | ||
| req(object); | ||
| req(dbname); | ||
| req(key); | ||
| checkObj(object); | ||
| checkStr(dbname); | ||
| checkStr(key); | ||
| if (sdp().keyExist(dbname, key)) { | ||
| let fl = sdp().getAll(dbname); | ||
| fl[key] = object; | ||
| let stfy = JSON.stringify(fl); | ||
| write("sdp", stfy) | ||
| return true; | ||
| } else { | ||
| throw new Error("Key not exist"); | ||
| } | ||
| } | ||
| } | ||
| /** | ||
| * Function is intended to save on "resources" by returning boolean values rather than committing to the process of retrieving, parsing, and returning file data. | ||
| * | ||
| * @param {Object | String} data Provide the identifier of a file to view if it currently exists. | ||
| * @returns {boolean} | ||
| */ | ||
| check(data) { | ||
| try { | ||
| return fs.existsSync(`${this.path}${data.id || data}.json`); | ||
| } catch(err) { | ||
| console.log("Error: " + err.message); | ||
| } | ||
| } | ||
| /** | ||
| * Returns the total amount of files in the default or given directory where data is read/written. | ||
| * @returns {Number} | ||
| */ | ||
| size() { | ||
| try { | ||
| let files = fs.readdirSync(`${this.path}`); | ||
| return files.length; | ||
| }catch(err) { | ||
| console.log("Error: " + err.message); | ||
| } | ||
| } | ||
| /** | ||
| * Deletes the specified JSON file. | ||
| * @param {Object | String} data Identifier of the file. | ||
| */ | ||
| delete(data) { | ||
| try { | ||
| fs.rmSync(`${this.path}${data.id || data}.json`); | ||
| this.feedback == true ? console.log("Successfully deleted 1 document.") : ""; | ||
| } catch(err) { | ||
| console.log("Error: " + err.message); | ||
| } | ||
| } | ||
| } | ||
| module.exports.wastefuldb; | ||
| module.exports = sdp; |
+1
-1
| { | ||
| "name": "superjson-db", | ||
| "version": "1.0.0", | ||
| "version": "1.0.1", | ||
| "description": "SuperJson DB - library javascript for DB easy and flash", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
+1
-152
| # SuperJson | ||
| A little custom made, document-oriented database project made with JavaScript and JSON for convenience. | ||
| ### Setup | ||
| ```js | ||
| const Wasteful = require('SuperJson'); | ||
| const db = new Wasteful({feedback: true, path: `${__dirname}/data/`, serial: true}); | ||
| ``` | ||
| ### Overall Requirements: | ||
| - `NodeJS v14.17.6 or higher` | ||
| - `NPM v6.14.15 or higher` | ||
| ### Functions | ||
| ```js | ||
| /* | ||
| db.insert(); | ||
| db.find(); | ||
| db.get(); | ||
| db.delete(); | ||
| db.update(); | ||
| db.collect(); | ||
| db.size(); | ||
| db.check(); | ||
| */ | ||
| db.insert({id: "1234", name: "seth", pass: "xyz"}); // An "id" variable is required in every insertion. | ||
| db.find({id: "1234"}); // Functions with or without an object for the identifier. | ||
| db.get("1234", (result) => { | ||
| console.log(result); | ||
| }) | ||
| db.update({id: "1234", element: "pass", change: "abc"}); | ||
| db.collect(); | ||
| db.size(); | ||
| db.check("1234"); | ||
| db.check({id: "1234"}); | ||
| db.delete({id: "1234"}); | ||
| db.delete("1234"); | ||
| ``` | ||
| ## SuperJson Interface | ||
| (Only available in Github repo) | ||
| A newly developed form of interacting with your data stored via SuperJson; A command-line interface which could be used for quick changes or personal usage without the hastle of typing a whole new set of code. | ||
| The interface file can be found within the "`SuperJson`" folder likely located in your `node_modules` folder and is named "**SuperJson Interface**"! (A shortcut to "wastefulbat" for design reasons.) | ||
| When launching the interface, you simple press a number listed in the options menu, press enter, and provide the information needed to execute an action! | ||
| ### Interface Requirement(s): | ||
| - `npm i chalk` (this should already be installed in the package itself) | ||
| ___ | ||
| ### In Depth | ||
| ```js | ||
| new Wasteful({feedback: true, path: `${__dirname}/info/`}); | ||
| ``` | ||
| * feedback - Sends a confirmation via console when a function is executed successfully. (__default__: false) | ||
| * path - Provide a custom path where you wish JSON files to be written/read. (__default__: .../SuperJson/data/) | ||
| * serial - Automatically assigns filenames/identifiers based on the size of the set path. (__default__: false) | ||
| ___ | ||
| ## .insert() | ||
| #### Insert a file with as many variables as you wish. __Always__ include an "id" variable as that is what is use to read the JSON document in most cases. | ||
| ```js | ||
| db.insert({id: "1234", name: "seth", pass: "xyz"}); | ||
| ``` | ||
| * id - The name of the file and what will be used in the .find() function | ||
| ___ | ||
| ## .find() | ||
| #### Provides the information of the specified file with the matching identifier. | ||
| ```js | ||
| let info = db.find({id: "1234"}); | ||
| console.log(info); | ||
| ``` | ||
| * id - The identifier of the file to find and display the information of. | ||
| ___ | ||
| ## .get() | ||
| #### Unlike `db.find`, `db.get` will read each JSON file within the directory and read each identifier within to locate the specified file. | ||
| ```js | ||
| db.get({id: "4321"}, async(res) => { console.log(await res) }); | ||
| ``` | ||
| * id - The internal identifier of a file. | ||
| ___ | ||
| ## .update() (by identifier) | ||
| #### Update a specific element within the specified file. If the element within the file doesn't exist, the function will automatically add the element as well as what was going to be changed. Not recommended when serialization is enabled. | ||
| ```js | ||
| db.update({id: "1234", element: "id", change: "4321", math: false}); | ||
| ``` | ||
| * id - The name/id of the file to update | ||
| * element - What element of the file you want to update | ||
| * change - What change you want to make to it | ||
| * math? - Does the change require (simple) math? | ||
| ___ | ||
| ## .update() (by element content) | ||
| #### Searches through every file within the directory, attempting to match the element 'name' and it's 'content'. When found, updates the specified element within the file. Recommended when serialization is enabled. | ||
| ```js | ||
| db.update({element: "age", change: 1, math: true}, {name: "animal", content: "fox"}); | ||
| ``` | ||
| * name - The name of an element within a file to check. | ||
| * content - The contents to be matched with the contents of the given element. | ||
| ___ | ||
| ## .update() (child element) | ||
| #### Update the value of an element's "child" or sub-value of the given element. "Child" is referred to as a nested collection element/value within your file. | ||
| ```js | ||
| db.update({element: "name", child: "first", change: "Mike", math: false}, {name: "animal", content: "fox"}); | ||
| ``` | ||
| * element - The parent element within a file which houses the child element (i.e nested collection). | ||
| * child - The child of the provided 'element' to be changed. | ||
| ___ | ||
| ## .collect({id?, element?}) | ||
| #### Reads, parses, then pushes information from each JSON file into one collection. Provide an id and/or element to further filter through each file. | ||
| ```js | ||
| let data = db.collect(); | ||
| data.forEach(info => { | ||
| if(info.active == true) { | ||
| console.log(info); | ||
| } else { | ||
| return; | ||
| } | ||
| }) | ||
| ``` | ||
| SuperJson DB - library javascript for DB easy and flash |
| {"serial":true,"feed":true} |
-253
| const rl = require('readline'); | ||
| const chalk = require("chalk"); | ||
| const readline = rl.createInterface({ | ||
| input: process.stdin, | ||
| output: process.stdout | ||
| }) | ||
| const Wasteful = require('./index.js'); | ||
| const fs = require('fs'); | ||
| const { WSAEINPROGRESS } = require('constants'); | ||
| let config = fs.readFileSync("./config.json"); config = JSON.parse(config); | ||
| const db = new Wasteful({feedback: config.feed, path: config.path, serial: config.serial}); | ||
| function wipe() { | ||
| for(let i = 0; i < 50; i++) { | ||
| console.log(" "); | ||
| } | ||
| } | ||
| function configSetup() { | ||
| wipe(); | ||
| readline.question(`${chalk.underline("Configurations")}\n1) Serialization ( ${chalk.cyan(config.serial)} )\n2) Feedback ( ${chalk.cyan(config.feed)} )\nType 'end' to exit.\n`, function(configCheck) { | ||
| switch(configCheck) { | ||
| case "1": | ||
| //config.serial == false ? updates.push({serial: true}) : updates.push({serial: false}); | ||
| config.serial == false ? config.serial = true : config.serial = false; | ||
| console.log(`Serialization: ${config.serial}`); | ||
| configSetup(); | ||
| break; | ||
| case "2": | ||
| config.feed == false ? config.feed = true : config.feed = false; | ||
| console.log(`Feedback: ${config.feed}`); | ||
| configSetup(); | ||
| break; | ||
| case "end": | ||
| console.log("Exiting configuration setup..."); | ||
| fs.writeFileSync(`./config.json`, JSON.stringify(config)); | ||
| wipe(); | ||
| repeater(); | ||
| break; | ||
| } | ||
| }); | ||
| } | ||
| function info() { | ||
| wipe(); | ||
| readline.question(`${chalk.underline.green("SuperJson Help / Info")}\n \n${chalk.yellow(">")} You can type ${chalk.green("end")} at any time during a process to return to the options menu.\n \n${chalk.yellow(">")} Enabling ${chalk.blue("serialization")} in the configuration automatically assigns identifiers to files so you don't have to.\nType 'end' to return to the menu.\n`, function (answer) { | ||
| if(answer == "end") { | ||
| return repeater(); | ||
| } | ||
| }) | ||
| } | ||
| function del() { | ||
| wipe(); | ||
| let data = {} | ||
| readline.question(`Do you have the unique identifier (i.e file name) of the document? ( ${chalk.yellow("y / n")} )\n`, function(answer){ | ||
| if(answer == "y") { | ||
| try { | ||
| readline.question("Provide the identifier of the file.\n", function(identifier) { | ||
| let check = db.check(identifier); | ||
| if(check == false) { | ||
| readline.question(`${chalk.red("Err")}: No file matching the given ID exists.\nType 'end' to exit or type 'retry' to try again.\n`, function(res) { | ||
| if(res == "end") { | ||
| repeater(); | ||
| } else if(res == "retry") { | ||
| del(); | ||
| } | ||
| }) | ||
| } else { | ||
| db.delete(identifier); | ||
| repeater(); | ||
| } | ||
| }) | ||
| } catch(err) { | ||
| console.log(err); | ||
| } | ||
| } else if(answer == "n") { | ||
| readline.question(`Provide a ${chalk.underline("field name")} within a file.\n`, function(fieldName) { | ||
| if(fieldName == "end") return repeater(); | ||
| data["name"] = fieldName; | ||
| readline.question(`Provide the ${chalk.underline("value")} inside your given field.\n`, function(fieldContent) { | ||
| data["content"] = fieldContent; | ||
| db.delete(data); | ||
| repeater(); | ||
| }) | ||
| }) | ||
| } | ||
| }) | ||
| } | ||
| function repeater () { | ||
| wipe(); | ||
| readline.question(`${chalk.underline.green("SuperJson's Beta Interface")}\n \n` + `${chalk.cyan("1")}) Configuration\n${chalk.cyan("2")}) Insert document\n${chalk.cyan("3")}) Find document\n${chalk.cyan("4")}) Update document\n${chalk.cyan("5")}) Delete document\n${chalk.cyan("6")}) Help / Info\n`, function(answer) { | ||
| switch(answer) { | ||
| case "1": | ||
| configSetup(); | ||
| break; | ||
| case "2": | ||
| insert(); | ||
| break; | ||
| case "3": | ||
| findSimple(); | ||
| break; | ||
| case "4": | ||
| update(); | ||
| break; | ||
| case "5": | ||
| del(); | ||
| break; | ||
| case "6": | ||
| info(); | ||
| break; | ||
| } | ||
| repeater(); | ||
| }) | ||
| } | ||
| function update() { | ||
| let updater = {} | ||
| let fieldman = {} | ||
| readline.question(`Which method do you wish to update the file? ${chalk.yellow("id")} or ${chalk.yellow("field")}?\n`, function(answer) { | ||
| if(answer == "end") return repeater(); | ||
| if(answer == "id") { | ||
| readline.question("Provide the identifier of the file you wish to update.\n", function(identifier) { | ||
| if(identifier == "end") return repeater(); | ||
| updater["id"] = identifier; | ||
| readline.question(`${chalk.blue("ID:")} ${identifier}\nProvide the element within the file you wish to update.\n`, function(element) { | ||
| if(element == "end") return repeater(); | ||
| updater["element"] = element; | ||
| readline.question(`${chalk.blue("ID:")} ${identifier}\n${chalk.blue("Element:")} ${element}\nProvide the change you wish to make.\n`, function(change) { | ||
| if(change == "end") return repeater(); | ||
| updater["change"] = change; | ||
| readline.question(`${chalk.blue("ID:")} ${identifier}\n${chalk.blue("Element:")} ${element}\n${chalk.blue("Change:")} ${change}\nDoes this update require math? ${chalk.yellow("(y / n)")}\n`, function(math){ | ||
| if(math == "y") { | ||
| updater["math"] = true; | ||
| console.log(updater) | ||
| db.update(updater); | ||
| repeater(); | ||
| } else if(math == "n") { | ||
| updater["math"] = false; | ||
| console.log(updater) | ||
| db.update(updater); | ||
| repeater(); | ||
| } else if(math == "end") { | ||
| repeater(); | ||
| } | ||
| }) | ||
| }) | ||
| }) | ||
| }) | ||
| } else if(answer == "field") { | ||
| readline.question(`Provide the field ${chalk.underline("name")} contained within a file.\n`, function(searchName) { | ||
| if(searchName == "end") return repeater(); | ||
| fieldman["name"] = searchName; | ||
| readline.question(`Provide the field's (${searchName}) ${chalk.underline("value")} attached to it.\n`, function(searchValue) { | ||
| if(searchValue == "end") return repeater(); | ||
| fieldman["content"] = searchValue; | ||
| readline.question(`Provide the element within the file you wish to update.\n`, function(element) { | ||
| if(element == "end") return repeater(); | ||
| updater["element"] = element | ||
| readline.question(`${chalk.blue("Element:")} ${element}\nProvide the change you wish to make.\n`, function(change) { | ||
| if(change == "end") return repeater(); | ||
| updater["change"] = change; | ||
| readline.question(`${chalk.blue("Element:")} ${element}\n${chalk.blue("Change:")} ${change}\nDoes this update require math? (${chalk.yellow("(y / n)")})\n`, function(math) { | ||
| if(math == "y") { | ||
| updater["math"] = true; | ||
| db.update(updater, fieldman); | ||
| repeater(); | ||
| } else if(math == "n") { | ||
| updater["math"] = false; | ||
| db.update(updater, fieldman); | ||
| repeater(); | ||
| } else if(math == "end") { | ||
| return repeater(); | ||
| } | ||
| }) | ||
| }) | ||
| }) | ||
| }) | ||
| }) | ||
| } | ||
| }) | ||
| } | ||
| function findSimple() { | ||
| wipe(); | ||
| readline.question(`Provide the ${chalk.blue("identifier")} of the file!\n`, function(id) { | ||
| if(id == "end") return repeater(); | ||
| let info = db.find(id); | ||
| if(!info) { | ||
| readline.question("Type 'end' to exit or type 'retry' to retry.\n", function(answer) { | ||
| if(answer == "end") { | ||
| repeater(); | ||
| } else if(answer == "retry") { | ||
| findSimple(); | ||
| } | ||
| }) | ||
| } else { | ||
| console.log(info); | ||
| readline.question("Type 'end' to exit or type 'retry' to try another search.\n", function(answer) { | ||
| if(answer == "end") { | ||
| repeater(); | ||
| } else if(answer == "retry") { | ||
| findSimple(); | ||
| } | ||
| }) | ||
| } | ||
| }) | ||
| } | ||
| let data = {} | ||
| function insert() { | ||
| wipe(); | ||
| let finalizer; | ||
| if(config.serial == false && (Object.keys(data)).includes("id") == false) { | ||
| readline.question(`Provide your file's ${chalk.underline("unique")} identifier: `, function(identifier) { | ||
| if(identifier == "end") return repeater(); | ||
| data["id"] = identifier | ||
| insert(); | ||
| }) | ||
| } else { | ||
| readline.question("Field name: ", function(name) { | ||
| if(name == "end" && (Object.keys(data)).length > 0) { | ||
| finalizer = data; | ||
| db.insert(finalizer); | ||
| return repeater(); | ||
| } else if(name == "end" && (Object.keys(data)).length == 0) { | ||
| return repeater(); | ||
| } | ||
| wipe(); | ||
| readline.question(`Field name: ${name}\nField value: `, function(value) { | ||
| if(value == "end" && (Object.keys(data)).length > 0) { | ||
| finalizer = data; finalizer = JSON.stringify(finalizer); | ||
| db.insert(finalizer); | ||
| let i=0; | ||
| while((Object.keys(data)).length > 0) { | ||
| data[i] = ""; | ||
| i++; | ||
| } | ||
| return repeater(); | ||
| } else if(name == "end" && (Object.keys(data)).length == 0) { | ||
| return repeater(); | ||
| } | ||
| data[name] = (Number(value) || value.toString()); | ||
| insert(); | ||
| }) | ||
| }) | ||
| } | ||
| } | ||
| repeater(); |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
2
-33.33%8155
-72.06%3
-40%242
-50.41%2
-98.7%1
Infinity%