@synet/patterns
Version:
Robust, battle-tested collection of stable patterns used in Synet packages
85 lines (84 loc) • 2.88 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnitFileSystem = exports.FileUnit = void 0;
const patterns_1 = require("../patterns");
const result_1 = require("../patterns/result");
class FileUnit extends patterns_1.ValueObject {
constructor(props) {
super(props);
}
static create(props) {
if (!props || typeof props.data !== 'string') {
return result_1.Result.fail('Invalid file unit properties: data must be a string');
}
if (!props.format || typeof props.format !== 'string') {
return result_1.Result.fail('Invalid file unit properties: format must be a string');
}
const unit = new FileUnit(props);
return result_1.Result.success(unit);
}
static fromJSON(json) {
try {
const data = JSON.parse(json);
return FileUnit.create(data);
}
catch (error) {
console.error(`Failed to parse JSON: ${error instanceof Error ? error.message : String(error)}`);
return result_1.Result.fail(`Invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
}
}
toJSON() {
try {
return JSON.stringify(this.props.data);
}
catch (error) {
throw new Error(`Failed to serialize unit to JSON: ${error instanceof Error ? error.message : String(error)}`);
}
}
get data() {
return this.props.data;
}
}
exports.FileUnit = FileUnit;
/**
* Basic file system implementation
* The foundation that everything builds on
*/
class UnitFileSystem {
constructor(filesystem, options) {
this.filesystem = filesystem;
this.options = options;
this.name = options?.name || 'UnitSystem';
}
async readFile(path) {
const file = await this.filesystem.readFile(path);
if (!file) {
throw new Error(`File not found: ${path}`);
}
const unit = FileUnit.fromJSON(file);
if (unit.isFailure) {
throw new Error(`Failed to create unit from file: ${unit.errorMessage}`);
}
return unit.value.data.toString();
}
async writeFile(path, props) {
const fileUnit = FileUnit.create({
data: props.data,
format: props.format,
});
if (fileUnit.isFailure) {
throw new Error(`Failed to create file unit: ${fileUnit.errorMessage}`);
}
if (fileUnit.isFailure) {
throw new Error(`Failed to create unit from data: ${fileUnit.errorMessage}`);
}
this.filesystem.writeFile(path, fileUnit.value.toJSON());
}
async deleteFile(path) {
this.filesystem.deleteFile(path);
}
async exists(path) {
return this.filesystem.exists(path);
}
}
exports.UnitFileSystem = UnitFileSystem;