improve local db utils

Signed-off-by: Arthur Lu <learthurgo@gmail.com>
This commit is contained in:
Arthur Lu 2023-02-27 23:11:51 +00:00
parent 940f41875b
commit f65772d6e4

22
db.js
View File

@ -23,7 +23,7 @@ function init () {
* @returns {boolean} whether the user is approved to allocate requested resources * @returns {boolean} whether the user is approved to allocate requested resources
*/ */
function requestResources (user, resources) { function requestResources (user, resources) {
Object.keys(resources).forEach((element) => { Object.keys(db[user]).forEach((element) => {
if (db[user][element] < resources[element]) { if (db[user][element] < resources[element]) {
return false; return false;
} }
@ -38,14 +38,18 @@ function requestResources (user, resources) {
* @returns {boolean} true if resources were successfully allocated, false otherwise * @returns {boolean} true if resources were successfully allocated, false otherwise
*/ */
function allocateResources (user, resources) { function allocateResources (user, resources) {
Object.keys(resources).forEach((element) => { let newdb = {};
db[user][element] -= resource[element]; Object.assign(newdb, db);
Object.keys(db[user]).forEach((element) => {
newdb[user][element] -= resource[element];
}); });
try { try {
fs.writeFileSync(filename, db); fs.writeFileSync(filename, newdb);
Object.assign(db, newdb);
return true; return true;
} }
catch { catch {
fs.writeFileSync(filename, db)
return false; return false;
} }
} }
@ -57,14 +61,18 @@ function allocateResources (user, resources) {
* @returns {boolean} true if resources were successfully deallocated, false otherwise * @returns {boolean} true if resources were successfully deallocated, false otherwise
*/ */
function releaseResources (user, resources) { function releaseResources (user, resources) {
Object.keys(resources).forEach((element) => { let newdb = {};
db[user][element] += resource[element]; Object.assign(newdb, db);
Object.keys(db[user]).forEach((element) => {
newdb[user][element] += resource[element];
}); });
try { try {
fs.writeFileSync(filename, db); fs.writeFileSync(filename, newdb);
Object.assign(db, newdb);
return true; return true;
} }
catch { catch {
fs.writeFileSync(filename, db)
return false; return false;
} }
} }