91 lines
1.9 KiB
JavaScript
91 lines
1.9 KiB
JavaScript
|
|
const fs = require('fs');
|
||
|
|
const location = './state'
|
||
|
|
|
||
|
|
if(!fs.existsSync(location)) {
|
||
|
|
fs.mkdir(location, err => {
|
||
|
|
if(err) { console.error(err); }
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
function l (id) { return `${location}/${id}.json` }
|
||
|
|
|
||
|
|
function c (id) {
|
||
|
|
let path = l(id);
|
||
|
|
if(fs.existsSync(path)) {
|
||
|
|
console.info(`[${id}] State already exists`);
|
||
|
|
} else {
|
||
|
|
fs.writeFile(path, JSON.stringify({}), err => {
|
||
|
|
if(err) {
|
||
|
|
console.error(err);
|
||
|
|
} else {
|
||
|
|
console.info(`[${id}] Created new state`);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function r (id) {
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
let path = l(id);
|
||
|
|
if(fs.existsSync(path)) {
|
||
|
|
console.info(`[${id}] Reading existing state`);
|
||
|
|
fs.readFile(path, (err, data) => {
|
||
|
|
if(err) {
|
||
|
|
console.error(err);
|
||
|
|
reject(err);
|
||
|
|
} else {
|
||
|
|
console.info(`[${id}] Read state`);
|
||
|
|
try {
|
||
|
|
let state = JSON.parse(data);
|
||
|
|
console.info(`[${id}] Deserialized state`);
|
||
|
|
resolve(state);
|
||
|
|
} catch(err) {
|
||
|
|
reject(err);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
});
|
||
|
|
} else {
|
||
|
|
console.error(`[${id}] Failed to locate state`);
|
||
|
|
reject(new Error('State not found.'));
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
function u (id, state) {
|
||
|
|
let path = l(id);
|
||
|
|
if(fs.existsSync(path)) {
|
||
|
|
fs.writeFile(path, JSON.stringify(state), err => {
|
||
|
|
if(err) {
|
||
|
|
console.error(err);
|
||
|
|
} else {
|
||
|
|
console.info(`[${id}] Updated state`);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
} else {
|
||
|
|
console.error(`[${id}] Failed to locate state`);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function d (id) {
|
||
|
|
let path = l(id);
|
||
|
|
if(fs.existsSync(path)) {
|
||
|
|
fs.unlink(path, err=> {
|
||
|
|
if(err) {
|
||
|
|
console.error(err);
|
||
|
|
} else {
|
||
|
|
console.info(`[${id}] Removed state`);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
} else {
|
||
|
|
console.error(`[${id}] Failed to locate state`);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
module.exports = {
|
||
|
|
create: c,
|
||
|
|
read: r,
|
||
|
|
update: u,
|
||
|
|
delete: d
|
||
|
|
}
|