add basic local db utility functions
This commit is contained in:
parent
71d793aabb
commit
a296550349
3
.gitignore
vendored
3
.gitignore
vendored
@ -1,3 +1,4 @@
|
||||
**/package-lock.json
|
||||
**/node_modules
|
||||
**/vars.js
|
||||
**/vars.js
|
||||
**/localdb.json
|
46
db.js
46
db.js
@ -2,10 +2,19 @@ const fs = require("fs");
|
||||
|
||||
filename = "localdb.json";
|
||||
|
||||
let db = {};
|
||||
|
||||
/**
|
||||
* called at app startup, can be used to initialize any variables needed for database access
|
||||
*/
|
||||
function init () {}
|
||||
function init () {
|
||||
try {
|
||||
db = fs.readFileSync(filename);
|
||||
}
|
||||
catch {
|
||||
fs.writeFileSync(filename, JSON.stringify(db));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* user requests additional resources specified in k-v pairs
|
||||
@ -13,7 +22,14 @@ function init () {}
|
||||
* @param {Object} resources k-v pairs with resource name as keys and resource ammount as values
|
||||
* @returns {boolean} whether the user is approved to allocate requested resources
|
||||
*/
|
||||
function requestResources (user, resources) {}
|
||||
function requestResources (user, resources) {
|
||||
Object.keys(resources).forEach((element) => {
|
||||
if (db[user][element] < resources[element]) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* user allocates additional resources specified in k-v pairs
|
||||
@ -21,7 +37,18 @@ function requestResources (user, resources) {}
|
||||
* @param {Object} resources k-v pairs with resource name as keys and resource ammount as values
|
||||
* @returns {boolean} true if resources were successfully allocated, false otherwise
|
||||
*/
|
||||
function allocateResources (user, resources) {}
|
||||
function allocateResources (user, resources) {
|
||||
Object.keys(resources).forEach((element) => {
|
||||
db[user][element] -= resource[element];
|
||||
});
|
||||
try {
|
||||
fs.writeFileSync(filename, db);
|
||||
return true;
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* user releases allocated resources specified in k-v pairs
|
||||
@ -29,6 +56,17 @@ function allocateResources (user, resources) {}
|
||||
* @param {Object} resources k-v pairs with resource name as keys and resource ammount as values
|
||||
* @returns {boolean} true if resources were successfully deallocated, false otherwise
|
||||
*/
|
||||
function releaseResources (user, resources) {}
|
||||
function releaseResources (user, resources) {
|
||||
Object.keys(resources).forEach((element) => {
|
||||
db[user][element] += resource[element];
|
||||
});
|
||||
try {
|
||||
fs.writeFileSync(filename, db);
|
||||
return true;
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {init, requestResources, releaseResources};
|
Loading…
Reference in New Issue
Block a user