2020-08-26 04:54:58 +02:00
|
|
|
const fs = require('fs');
|
|
|
|
const crypto = require('crypto');
|
2011-11-18 23:54:57 +01:00
|
|
|
|
2020-08-26 04:54:58 +02:00
|
|
|
const winston = require('winston');
|
2011-11-18 23:54:57 +01:00
|
|
|
|
|
|
|
// For storing in files
|
2011-11-22 04:03:50 +01:00
|
|
|
// options[type] = file
|
|
|
|
// options[path] - Where to store
|
2011-11-18 23:54:57 +01:00
|
|
|
|
2020-08-29 00:06:49 +02:00
|
|
|
class FileDocumentStore {
|
|
|
|
|
|
|
|
constructor(options){
|
|
|
|
this.basePath = options.path || './data';
|
|
|
|
this.expire = options.expire;
|
|
|
|
}
|
|
|
|
|
|
|
|
//save data in a file, key as md5 - since we don't know what we can passed here
|
|
|
|
set(key, data, callback, skipExpire){
|
2020-08-28 04:39:03 +02:00
|
|
|
const _this = this;
|
2020-08-29 00:06:49 +02:00
|
|
|
const filePath = this.getPath(key);
|
|
|
|
|
|
|
|
try {
|
|
|
|
if (!fs.existsSync(this.basePath)){
|
|
|
|
winston.debug('creating data storage directory', { filename: this.basePath });
|
|
|
|
fs.mkdirSync(this.basePath, {mode: '700'});
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
fs.writeFileSync(filePath, data);
|
|
|
|
callback(true);
|
|
|
|
if (_this.expire && !skipExpire){
|
|
|
|
winston.warn('file store cannot set expirations on keys', { file: filePath });
|
2020-08-28 04:39:03 +02:00
|
|
|
}
|
2020-08-29 00:06:49 +02:00
|
|
|
}
|
|
|
|
catch (err){
|
|
|
|
winston.error('error while writing document to file', { file: filePath, error: err });
|
|
|
|
callback(false);
|
|
|
|
}
|
2020-08-28 04:39:03 +02:00
|
|
|
}
|
2020-08-29 00:06:49 +02:00
|
|
|
catch (err){
|
|
|
|
winston.error('error while creating dir', { path: _this.basePath, error: err });
|
|
|
|
return callback(false);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//get data from a file
|
|
|
|
get(key, callback, skipExpire){
|
|
|
|
const _this = this;
|
|
|
|
const filePath = this.getPath(key);
|
|
|
|
|
|
|
|
try {
|
|
|
|
winston.silly('get key', { type: 'file', filename: filePath });
|
|
|
|
let data = fs.readFileSync(filePath).toString();
|
2020-08-28 04:39:03 +02:00
|
|
|
callback(data);
|
|
|
|
if (_this.expire && !skipExpire){
|
2020-08-29 00:06:49 +02:00
|
|
|
winston.warn('file store cannot set expirations on keys', { file: filePath });
|
2020-08-28 04:39:03 +02:00
|
|
|
}
|
|
|
|
}
|
2020-08-29 00:06:49 +02:00
|
|
|
catch (err){
|
|
|
|
winston.debug('error while reading document', { file: filePath, error: err });
|
|
|
|
return callback(false);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//generate a md5 hash of a key
|
|
|
|
getPath(str){
|
|
|
|
return require('path').join(this.basePath, crypto.createHash('md5').update(str).digest('hex'));
|
|
|
|
}
|
|
|
|
}
|
2011-11-18 23:54:57 +01:00
|
|
|
|
|
|
|
module.exports = FileDocumentStore;
|