@webda/core
Version:
Expose API with Lambda
188 lines • 5.64 kB
JavaScript
import * as fs from "fs";
import * as path from "path";
import { JSONUtils } from "../utils/serializers.js";
import { Store, StoreNotFoundError, StoreParameters } from "./store.js";
class FileStoreParameters extends StoreParameters {
}
/**
* Simple file storage of object
*
* Storage structure
* /folder/{uuid}
*
*
* Parameters:
* folder: to store to
*
* @category CoreServices
* @WebdaModda
*/
class FileStore extends Store {
/**
* Load the parameters for a service
*/
loadParameters(params) {
return new FileStoreParameters(params, this);
}
/**
* Create the storage folder if does not exist
*/
computeParameters() {
super.computeParameters();
if (!fs.existsSync(this.parameters.folder)) {
fs.mkdirSync(this.parameters.folder);
}
}
/**
* Get the file path of an object
* @param uid of the object
* @returns
*/
file(uid) {
return `${this.parameters.folder}/${uid}${FileStore.EXTENSION}`;
}
/**
* @override
*/
async _exists(uid) {
return fs.existsSync(this.file(uid));
}
/**
* @override
*/
async find(query) {
const files = fs
.readdirSync(this.parameters.folder)
.filter(file => {
return !fs.statSync(path.join(this.parameters.folder, file)).isDirectory();
})
.map(f => f.substring(0, f.length - FileStore.EXTENSION.length))
.sort();
return this.simulateFind(query, files);
}
/**
* @override
*/
async _save(object) {
fs.writeFileSync(this.file(object.getUuid()), JSON.stringify(object.toStoredJSON(), undefined, this.parameters.beautify));
return object;
}
/**
* @inheritdoc
*/
async _upsertItemToCollection(uid, prop, item, index, itemWriteCondition, itemWriteConditionField, updateDate) {
try {
// Need to keep sync to avoid conflicts
return await this.simulateUpsertItemToCollection(this.initModel(JSONUtils.loadFile(this.file(uid))), prop, item, updateDate, index, itemWriteCondition, itemWriteConditionField);
}
catch (err) {
throw new StoreNotFoundError(uid, this.getName());
}
}
/**
* @inheritdoc
*/
async _removeAttribute(uuid, attribute, writeCondition, writeConditionField) {
let res = await this._get(uuid, true);
this.checkUpdateCondition(res, writeConditionField, writeCondition);
delete res[attribute];
await this._save(res);
}
/**
* @inheritdoc
*/
async _deleteItemFromCollection(uid, prop, index, itemWriteCondition, itemWriteConditionField, updateDate) {
let res = await this._get(uid, true);
this.checkCollectionUpdateCondition(res, prop, itemWriteConditionField, itemWriteCondition, index);
res[prop].splice(index, 1);
res._lastUpdate = updateDate;
return this._save(res);
}
/**
* @inheritdoc
*/
async _delete(uid) {
const filePath = this.file(uid);
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
}
/**
* @inheritdoc
*/
async _patch(object, uid, writeCondition, writeConditionField) {
let stored = await this._get(uid, true);
this.checkUpdateCondition(stored, writeConditionField, writeCondition);
for (let prop in object) {
stored[prop] = object[prop];
}
return this._save(stored);
}
/**
* @override
*/
async _update(object, uid, writeCondition, writeConditionField) {
let stored = await this._get(uid, true);
this.checkUpdateCondition(stored, writeConditionField, writeCondition);
return this._save(this.initModel(object));
}
/**
* @override
*/
async getAll(uids) {
if (!uids) {
uids = [];
let files = fs.readdirSync(this.parameters.folder);
for (let file in files) {
uids.push(files[file].substring(0, files[file].length - FileStore.EXTENSION.length));
}
}
let result = [];
for (let i in uids) {
let model = this._get(uids[i]);
result.push(model);
}
return (await Promise.all(result)).filter(f => f !== undefined);
}
/**
* @override
*/
async _get(uid, raiseIfNotFound = false) {
let res = await this.exists(uid);
if (res) {
let data = JSON.parse(fs.readFileSync(this.file(uid)).toString());
if (data.__type !== this._modelType && this.parameters.strict) {
return undefined;
}
return this.initModel(data);
}
else if (raiseIfNotFound) {
throw new StoreNotFoundError(uid, this.getName());
}
}
/**
* @override
*/
async _incrementAttributes(uid, params, updateDate) {
let stored = await this._get(uid, true);
params.forEach(({ property: prop, value }) => {
if (stored[prop] === undefined) {
stored[prop] = 0;
}
stored._lastUpdate = updateDate;
stored[prop] += value;
});
stored._lastUpdate = updateDate;
return this._save(stored);
}
/**
* @override
*/
async __clean() {
// This is only during test
(await import("fs-extra")).emptyDirSync(this.parameters.folder);
}
}
FileStore.EXTENSION = ".json";
export { FileStore };
//# sourceMappingURL=file.js.map