Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active November 9, 2023 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/65f7b8c8c888e823827c000f9c2df486 to your computer and use it in GitHub Desktop.
Save code-boxx/65f7b8c8c888e823827c000f9c2df486 to your computer and use it in GitHub Desktop.
NodeJS Category Subcategory

NODEJS CATEGORY & SUBCATEGORY

https://code-boxx.com/category-subcategory-nodejs/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Install required modules - npm i better-sqlite3
    • Create the dummy database - node 1b-database.js
    • Run the demo - node 2-draw.js
  2. Also see 3-insert-update-delete.js for the "admin features".

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE category (
category_id INTEGER,
parent_id INTEGER DEFAULT 0,
category_name TEXT NOT NULL,
PRIMARY KEY("category_id" AUTOINCREMENT)
);
CREATE INDEX parent_id ON category (parent_id);
INSERT INTO `category` (`category_id`, `parent_id`, `category_name`) VALUES
(1, 0, 'Electronics'),
(2, 1, 'Computers'),
(3, 1, 'Cameras'),
(4, 2, 'Desktop'),
(5, 2, 'Laptop');
// npm install better-sqlite3
require("better-sqlite3")("category.db").exec(
require("fs").readFileSync("1a-database.sql", "utf8")
);
console.log("Database created.");
// (A) GET ALL CATEGORIES
const db = require("better-sqlite3")("category.db");
function getAll (id) {
let rows = db.prepare("SELECT * FROM `category` WHERE `parent_id` = ?").all(id);
if (rows.length==0) { return null; }
let data = {};
rows.forEach(row => {
data[row["category_id"]] = {
n : row["category_name"],
c : getAll(row["category_id"])
};
});
return data;
}
// (B) DRAW CATEGORIES
function draw (data, level) {
for (let [id, cat] of Object.entries(data)) {
let row = "";
if (level > 0) { for (i=0; i<level; i++) { row += " "; }}
row += `(${id}) ${cat["n"]}`;
console.log(row);
if (cat["c"] != null) { draw(cat["c"], level+1); }
}
}
draw(getAll(0), 0);
// (A) CONNECT TO DATABASE
const db = require("better-sqlite3")("category.db");
// (B) INSERT CATEGORY
let stmt = db.prepare("INSERT INTO `category` (`parent_id`, `category_name`) VALUES (?, ?)");
stmt.run(2, "Smartphones");
stmt.run(2, "Tablets");
// (C) UPDATE CATEGORY
stmt = db.prepare("UPDATE `category` SET `parent_id`=?, `category_name`=? WHERE `category_id`=?");
stmt.run(0, "Camerazzzz", 3);
// (D) GET CHILD CATEGORIES
function getChildren (id) {
let rows = db.prepare("SELECT `category_id` FROM `category` WHERE `parent_id`=?").pluck().all(id);
if (rows.length==0) { return null; }
rows.forEach(i => {
let children = getChildren(i);
if (children != null) { rows = rows.concat(children); }
});
return rows;
}
// (E) GET VALID "SWITCHABLE PARENT ID"
function getSwitchable (id) {
// (E1) CANNOT SWITCH TO CHILDREN & SELF
let illegal = getChildren(id);
if (illegal == null) { illegal = [id]; }
else { illegal.push(id); }
// (E2) GET "LEGAL CATEGORIES"
let rows = db.prepare(
"SELECT `category_id` FROM `category` WHERE `parent_id` NOT IN ("+illegal.join(",")+");"
).pluck().all();
rows.push(0);
return rows;
}
// (F) DELETE CATEGORY
function del (id) {
// (F1) REVERT CHILDREN TO "ROOT"
let stmt, children = getChildren(id);
if (children != null) {
stmt = db.prepare("UPDATE `category` SET `parent_id`=0 WHERE `category_id` IN ("+children.join(",")+")");
stmt.run();
}
// (F2) DELETE CATEGORY
stmt = db.prepare("DELETE FROM `category` WHERE `category_id`=?");
stmt.run(id);
}
del(2);
call npm i better-sqlite3
node 1b-database.js
node 2-draw.js
source "npm i better-sqlite3"
node ./1b-database.js
node ./2-draw.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment