generator-begcode
Version:
Spring Boot + Angular/React/Vue in one handy generator
66 lines (65 loc) • 2.28 kB
JavaScript
import path from 'path-browserify';
const VECTOR_FILENAME = 'vector.json';
const DOCUMENT_FILENAME = 'document.json';
export class LocalDocument {
id;
config;
_data;
constructor(id, config) {
this.id = id;
this.config = config;
}
vector() {
const vectorPath = path.join(this.config.uri, VECTOR_FILENAME);
if (!this.config.workspace.existsSync(vectorPath)) {
throw new Error(`Vector file for '${this.id}' does not exist: ${vectorPath}. Did you forget to call .save()?`);
}
const vectorFileContent = this.config.workspace.readFileSync(vectorPath);
const vector = JSON.parse(vectorFileContent);
return vector.vector;
}
text() {
if (!this._data) {
this.loadData();
}
return this._data.text;
}
metadata() {
if (!this._data) {
this.loadData();
}
return this._data.metadata;
}
save({ text, metadata, vector }) {
const docPath = this.config.uri;
const vectorPath = path.join(docPath, VECTOR_FILENAME);
const documentPath = path.join(docPath, DOCUMENT_FILENAME);
if (!this.config.workspace.existsSync(docPath)) {
this.config.workspace.mkdirSync(docPath, { recursive: true });
}
this.config.workspace.writeFileSync(vectorPath, JSON.stringify({
id: this.id,
vector,
}));
if (!metadata) {
metadata = {
index: this.config.workspace.readdirSync(docPath).length - 1,
};
}
const documentData = {
id: this.id,
text,
metadata,
};
this.config.workspace.writeFileSync(documentPath, JSON.stringify(documentData));
}
loadData() {
const documentPath = path.join(this.config.uri, DOCUMENT_FILENAME);
if (!this.config.workspace.existsSync(documentPath)) {
throw new Error(`Document file for '${this.id}' does not exist: ${documentPath}. Did you forget to call .save()?`);
}
const documentFileContent = this.config.workspace.readFileSync(documentPath);
const document = JSON.parse(documentFileContent);
this._data = document;
}
}