rosie-cli
Version:
AI-powered command-line interface tool that uses OpenAI's API to help you interact with your computer through natural language
90 lines (89 loc) • 3.62 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileStore = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
/**
* Generic file storage class that handles saving and loading data as JSON
* @template T The type of data to be stored
*/
class FileStore {
/**
* Creates a new FileStore instance
* @param filePath Path where the data will be stored
*/
constructor(filePath, defaultData) {
this.filePath = filePath;
// Ensure the directory exists
const directory = path_1.default.dirname(filePath);
if (!fs_1.default.existsSync(directory)) {
fs_1.default.mkdirSync(directory, { recursive: true });
}
if (!fs_1.default.existsSync(this.filePath)) {
// Create an empty file with default structure
// Determine the default structure based on the generic type T
// Write the default structure to the file
fs_1.default.writeFileSync(this.filePath, JSON.stringify(defaultData, null, 2), 'utf8');
}
}
/**
* Saves data to the file as JSON
* @param data The data to save
* @returns Promise that resolves when the data is saved
*/
save(data) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const jsonData = JSON.stringify(data, null, 2);
fs_1.default.writeFile(this.filePath, jsonData, 'utf8', (err) => {
if (err) {
reject(err);
}
else {
resolve();
}
});
});
});
}
/**
* Loads data from the file
* @returns Promise that resolves with the loaded data, or null if the file doesn't exist
*/
load() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
if (!fs_1.default.existsSync(this.filePath)) {
throw new Error(`File ${this.filePath} does not exist`);
}
fs_1.default.readFile(this.filePath, 'utf8', (err, data) => {
if (err) {
reject(err);
}
else {
try {
const parsedData = JSON.parse(data);
resolve(parsedData);
}
catch (parseErr) {
reject(parseErr);
}
}
});
});
});
}
}
exports.FileStore = FileStore;