keal
Version:
keal is key value storage
84 lines (67 loc) • 1.74 kB
JavaScript
const fs = require('fs');
const path = require('path');
class Keal {
constructor({ databasePath, databaseName } = {}) {
if (databasePath === undefined) {
throw 'databasePath is undefined. please set databasePath.';
}
if (databaseName === undefined) {
throw 'databaseName is undefined. please set databaseName.';
}
this.saveTimeoutId = null;
this.saveDelay = 500;
this.databasePath = databasePath;
this.databaseName = databaseName;
const time = this.getTime();
this.database = {
name: this.databaseName,
path: this.databasePath,
createdAt: time,
updatedAt: time,
data: {},
};
this.connect();
}
getTime() {
return new Date().getTime();
}
getFilePath() {
return path.join(this.databasePath, `${this.databaseName}.keal`);
}
connect() {
const filePath = this.getFilePath();
if (fs.existsSync(filePath)) {
const file = fs.readFileSync(filePath, { encoding: 'utf8' });
this.database = JSON.parse(file);
} else {
this.save();
}
}
put(key, value) {
this.database.updatedAt = this.getTime();
this.database.data[key] = value;
this.save();
}
get(key) {
return this.database.data[key];
}
gets(keys) {
return keys.map(key => {
return this.get(key);
})
}
save() {
clearTimeout(this.saveTimeoutId);
this.saveTimeoutId = setTimeout(() => {
const filePath = this.getFilePath();
fs.writeFileSync(filePath, JSON.stringify(this.database), { encoding: 'utf8' })
}, this.saveDelay);
}
keys() {
return Object.keys(this.database.data);
}
values() {
return Object.values(this.database.data);
}
}
module.exports = Keal;