keeweb/app/scripts/storage/io-file-cache.js

103 lines
3.0 KiB
JavaScript
Raw Normal View History

2019-09-15 14:16:32 +02:00
import { Launcher } from 'comp/launcher';
2017-04-08 17:34:27 +02:00
2020-06-01 16:53:51 +02:00
const IoFileCache = function (config) {
2017-04-08 17:34:27 +02:00
this.basePath = null;
this.cacheName = config.cacheName;
this.logger = config.logger;
};
2019-09-17 22:17:40 +02:00
Object.assign(IoFileCache.prototype, {
2017-04-08 17:34:27 +02:00
initFs(callback) {
if (this.basePath) {
return callback();
}
const basePath = Launcher.getUserDataPath(this.cacheName);
2020-06-01 16:53:51 +02:00
Launcher.mkdir(basePath, (err) => {
2017-04-08 17:34:27 +02:00
if (err) {
this.logger.error('Error creating plugin folder');
} else {
this.basePath = basePath;
}
callback(err);
});
},
resolvePath(path) {
return Launcher.joinPath(this.basePath, path);
},
save(id, data, callback) {
2020-06-01 16:53:51 +02:00
this.initFs((err) => {
2017-04-08 17:34:27 +02:00
if (err) {
return callback && callback(err, null);
}
this.logger.debug('Save', id);
const ts = this.logger.ts();
const path = this.resolvePath(id);
2020-06-01 16:53:51 +02:00
Launcher.writeFile(path, data, (err) => {
2017-04-08 17:34:27 +02:00
if (err) {
this.logger.error('Error saving file', id, err);
2019-08-16 23:05:39 +02:00
if (callback) {
callback(err);
}
2017-04-08 17:34:27 +02:00
} else {
this.logger.debug('Saved', id, this.logger.ts(ts));
2019-08-16 23:05:39 +02:00
if (callback) {
callback();
}
2017-04-08 17:34:27 +02:00
}
});
});
},
load(id, callback) {
2020-06-01 16:53:51 +02:00
this.initFs((err) => {
2017-04-08 17:34:27 +02:00
if (err) {
return callback && callback(err, null);
}
this.logger.debug('Load', id);
const ts = this.logger.ts();
const path = this.resolvePath(id);
Launcher.readFile(path, undefined, (data, err) => {
if (err) {
this.logger.error('Error loading file', id, err);
2019-08-16 23:05:39 +02:00
if (callback) {
callback(err);
}
2017-04-08 17:34:27 +02:00
} else {
this.logger.debug('Loaded', id, this.logger.ts(ts));
2019-08-16 23:05:39 +02:00
if (callback) {
callback(null, data);
}
2017-04-08 17:34:27 +02:00
}
});
});
},
remove(id, callback) {
2020-06-01 16:53:51 +02:00
this.initFs((err) => {
2017-04-08 17:34:27 +02:00
if (err) {
return callback && callback(err, null);
}
this.logger.debug('Remove', id);
const ts = this.logger.ts();
const path = this.resolvePath(id);
2020-06-01 16:53:51 +02:00
Launcher.deleteFile(path, (err) => {
2017-04-08 17:34:27 +02:00
if (err) {
this.logger.error('Error removing file', id, err);
2019-08-16 23:05:39 +02:00
if (callback) {
callback(err);
}
2017-04-08 17:34:27 +02:00
} else {
this.logger.debug('Removed', id, this.logger.ts(ts));
2019-08-16 23:05:39 +02:00
if (callback) {
callback();
}
2017-04-08 17:34:27 +02:00
}
});
});
}
});
2019-09-15 14:16:32 +02:00
export { IoFileCache };