protoobject
Version:
A universal class for creating any JSON objects and simple manipulations with them.
328 lines (327 loc) • 13 kB
JavaScript
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
import { randomUUID } from "node:crypto";
import { ProtoObject } from "./proto-object.js";
import { StaticImplements } from "../decorators/static-implements.js";
/* eslint-disable no-unused-vars, @typescript-eslint/no-shadow */
export var RecordState;
(function (RecordState) {
RecordState[RecordState["ACTIVE"] = 0] = "ACTIVE";
RecordState[RecordState["DELETED"] = 1] = "DELETED";
})(RecordState || (RecordState = {}));
/* eslint-enable no-unused-vars, @typescript-eslint/no-shadow */
/**
* A universal class for creating ProtoObject entities with SQLite integration
* Extends ProtoObject with database operations using node:sqlite
*/
let ProtoObjectSQLite = (() => {
let _classDecorators = [StaticImplements()];
let _classDescriptor;
let _classExtraInitializers = [];
let _classThis;
let _classSuper = ProtoObject;
var ProtoObjectSQLite = _classThis = class extends _classSuper {
constructor(data) {
super(data);
// Auto-initialize common fields if not provided
if (typeof this.record_state === "undefined") {
this.record_state = RecordState.ACTIVE;
}
if (!this.id) {
this.id = randomUUID();
}
const now = new Date();
if (!this.created_at) {
this.created_at = now;
}
if (!this.updated_at) {
this.updated_at = now;
}
return this;
}
/**
* Find record by ID
*/
static async getById(db, id) {
try {
const record = db
.prepare(`SELECT * FROM ${this.table} WHERE ${this.primaryKey} = ?`)
.get(id);
return record ? this.fromJSON(record) : undefined;
}
catch (error) {
console.error(`Error getting record by ID: ${error}`);
return undefined;
}
}
/**
* Find records by criteria
*/
static async findBy(db, criteria) {
try {
const whereClause = Object.keys(criteria)
.map((key) => `${key} = ?`)
.join(" AND ");
const sql = whereClause
? `SELECT * FROM ${this.table} WHERE ${whereClause}`
: `SELECT * FROM ${this.table}`;
const records = db
.prepare(sql)
.all(...Object.values(criteria));
return records.map((record) => this.fromJSON(record));
}
catch (error) {
console.error(`Error finding records: ${error}`);
return [];
}
}
/**
* Find one record by criteria
*/
static async findOneBy(db, criteria) {
const results = await this.findBy(db, criteria);
return results[0];
}
/**
* Count records matching criteria
*/
static async count(db, criteria) {
try {
if (!criteria || Object.keys(criteria).length === 0) {
const result = db
.prepare(`SELECT COUNT(*) as count FROM ${this.table}`)
.get();
return result.count;
}
const whereClause = Object.keys(criteria)
.map((key) => `${key} = ?`)
.join(" AND ");
const result = db
.prepare(`SELECT COUNT(*) as count FROM ${this.table} WHERE ${whereClause}`)
.get(...Object.values(criteria));
return result.count;
}
catch (error) {
console.error(`Error counting records: ${error}`);
return 0;
}
}
/**
* Create table for this entity
* Override in subclasses to define custom schema
*/
static async createTable(db) {
const sql = `
CREATE TABLE IF NOT EXISTS ${this.table} (
id TEXT PRIMARY KEY,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
record_state INTEGER NOT NULL DEFAULT 0
)
`;
db.prepare(sql).run();
}
/**
* Drop table for this entity
*/
static async dropTable(db) {
db.prepare(`DROP TABLE IF EXISTS ${this.table}`).run();
}
/**
* Reload current instance from database
*/
async reload(db) {
if (!this.id) {
throw new Error("Cannot reload record without ID");
}
const classNode = this.constructor;
const dbRecord = await classNode.getById(db, this.id);
if (!dbRecord) {
throw new Error(`Record with ID ${this.id} not found`);
}
return this.assign(dbRecord);
}
/**
* Save (insert or update) record to database
*/
async save(db) {
if (!this.id) {
throw new Error("Cannot save record without ID");
}
const classNode = this.constructor;
const existing = await classNode.getById(db, this.id);
if (existing) {
return this.update(db);
}
else {
return this.insert(db);
}
}
/**
* Insert new record
*/
async insert(db) {
const classNode = this.constructor;
this.created_at = new Date();
this.updated_at = new Date();
const jsonData = this.toJSON();
// Filter out undefined and null values
const validData = {};
Object.entries(jsonData).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
validData[key] = value;
}
});
if (Object.keys(validData).length === 0) {
throw new Error("No valid data to insert");
}
const columns = Object.keys(validData);
const placeholders = columns.map(() => "?").join(", ");
const sql = `INSERT INTO ${classNode.table} (${columns.join(", ")}) VALUES (${placeholders})`;
try {
db.prepare(sql).run(...Object.values(validData));
return this;
}
catch (error) {
console.error(`Error inserting record: ${error}`);
throw error;
}
}
/**
* Update existing record
*/
async update(db) {
if (!this.id) {
throw new Error("Cannot update record without ID");
}
const classNode = this.constructor;
this.updated_at = new Date();
const jsonData = this.toJSON();
delete jsonData[classNode.primaryKey];
const setClause = Object.keys(jsonData)
.map((key) => `${key} = ?`)
.join(", ");
const sql = `UPDATE ${classNode.table} SET ${setClause} WHERE ${classNode.primaryKey} = ?`;
try {
db.prepare(sql).run(...Object.values(jsonData), this.id);
return this;
}
catch (error) {
console.error(`Error updating record: ${error}`);
throw error;
}
}
/**
* Soft delete (mark as deleted)
*/
async softDelete(db) {
this.record_state = RecordState.DELETED;
return this.update(db);
}
/**
* Hard delete (remove from database)
*/
async delete(db) {
if (!this.id) {
throw new Error("Cannot delete record without ID");
}
const classNode = this.constructor;
try {
db.prepare(`DELETE FROM ${classNode.table} WHERE ${classNode.primaryKey} = ?`).run(this.id);
}
catch (error) {
console.error(`Error deleting record: ${error}`);
throw error;
}
}
/**
* Check if record exists in database
*/
async exists(db) {
if (!this.id) {
return false;
}
const classNode = this.constructor;
const existing = await classNode.getById(db, this.id);
return !!existing;
}
/**
* Enhanced fromJSON with Date parsing
*/
static fromJSON(data) {
const instance = new this();
Object.assign(instance, super.fromJSON(data));
if (typeof data.created_at === "string") {
instance.created_at = new Date(data.created_at);
}
if (typeof data.updated_at === "string") {
instance.updated_at = new Date(data.updated_at);
}
return instance;
}
/**
* Enhanced toJSON with Date serialization
*/
toJSON() {
const baseData = super.toJSON();
const result = { ...baseData };
if (this.created_at !== undefined)
result.created_at = this.created_at.toJSON();
if (this.updated_at !== undefined)
result.updated_at = this.updated_at.toJSON();
return result;
}
};
__setFunctionName(_classThis, "ProtoObjectSQLite");
(() => {
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
ProtoObjectSQLite = _classThis = _classDescriptor.value;
if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
})();
// Default table name - should be overridden in subclasses
_classThis.table = "proto_objects";
// Default primary key - can be overridden if needed
_classThis.primaryKey = "id";
(() => {
__runInitializers(_classThis, _classExtraInitializers);
})();
return ProtoObjectSQLite = _classThis;
})();
export { ProtoObjectSQLite };