quicklite
Version:
A lightweight ORM toolkit for SQLite in Node.js applications
205 lines • 7.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseService = void 0;
/**
* Base service class for CRUD operations on entities
*/
class BaseService {
/**
* Creates a new service for the specified entity
* @param db Database instance
* @param entityClass Entity class
*/
constructor(db, entityClass) {
this.db = db;
this.entityClass = entityClass;
this.tableInfo = entityClass.getTableInfo();
}
/**
* Inserts a new entity into the database
* @param entity Entity to insert
* @returns ID of the inserted entity
*/
insert(entity) {
const keys = Object.keys(entity);
const values = Object.values(entity);
const placeholders = keys.map(() => '?').join(', ');
const sql = `INSERT INTO ${this.tableInfo.name} (${keys.join(', ')}) VALUES (${placeholders})`;
const stmt = this.db.prepare(sql);
const result = stmt.run(...values);
return result.lastInsertRowid;
}
/**
* Inserts multiple entities in a single transaction
* @param entities Array of entities to insert
*/
batchInsert(entities) {
if (entities.length === 0)
return;
const transaction = this.db.transaction((items) => {
for (const item of items) {
this.insert(item);
}
});
transaction(entities);
}
/**
* Retrieves an entity by its ID
* @param id Entity ID
* @returns Entity or null if not found
*/
getById(id) {
const primaryKey = this.tableInfo.primaryKey || 'id';
const sql = `SELECT * FROM ${this.tableInfo.name} WHERE ${primaryKey} = ?`;
const stmt = this.db.prepare(sql);
const result = stmt.get(id);
return result || null;
}
/**
* Finds entities matching the specified criteria
* @param options Query options
* @returns Array of matching entities
*/
find(options = {}) {
let sql = `SELECT * FROM ${this.tableInfo.name}`;
const params = [];
// Handle WHERE conditions
if (options.where && Object.keys(options.where).length > 0) {
const whereConditions = Object.entries(options.where).map(([key, value]) => {
params.push(value);
return `${key} = ?`;
});
sql += ` WHERE ${whereConditions.join(' AND ')}`;
}
// Handle ORDER BY
if (options.orderBy) {
sql += ` ORDER BY ${options.orderBy}`;
}
// Handle pagination
if (options.limit !== undefined) {
sql += ` LIMIT ?`;
params.push(options.limit);
if (options.offset !== undefined) {
sql += ` OFFSET ?`;
params.push(options.offset);
}
}
const stmt = this.db.prepare(sql);
const results = stmt.all(...params);
return results;
}
/**
* Finds a single entity matching the specified criteria
* @param options Query options
* @returns Matching entity or null if not found
*/
findOne(options = {}) {
options.limit = 1;
const results = this.find(options);
return results.length > 0 ? results[0] : null;
}
/**
* Counts entities matching the specified criteria
* @param options Query options
* @returns Count of matching entities
*/
count(options = {}) {
let sql = `SELECT COUNT(*) as count FROM ${this.tableInfo.name}`;
const params = [];
// Handle WHERE conditions
if (options.where && Object.keys(options.where).length > 0) {
const whereConditions = Object.entries(options.where).map(([key, value]) => {
params.push(value);
return `${key} = ?`;
});
sql += ` WHERE ${whereConditions.join(' AND ')}`;
}
const stmt = this.db.prepare(sql);
const result = stmt.get(...params);
return (result === null || result === void 0 ? void 0 : result.count) || 0;
}
/**
* Updates an entity in the database
* @param entity Entity data to update
* @param whereCondition Optional WHERE condition (defaults to primary key)
* @returns Number of updated rows
*/
update(entity, whereCondition) {
const primaryKey = this.tableInfo.primaryKey || 'id';
const updateData = { ...entity };
// Handle case where primary key is in entity but no where condition is provided
if (primaryKey in updateData && !whereCondition) {
const id = updateData[primaryKey];
delete updateData[primaryKey];
whereCondition = { [primaryKey]: id };
}
if (!whereCondition || Object.keys(whereCondition).length === 0) {
throw new Error('Update operation requires a condition');
}
const updateKeys = Object.keys(updateData);
if (updateKeys.length === 0) {
return 0;
}
const updateValues = Object.values(updateData);
const wherePairs = Object.entries(whereCondition);
const whereValues = wherePairs.map(p => p[1]);
const sql = `
UPDATE ${this.tableInfo.name}
SET ${updateKeys.map(key => `${key} = ?`).join(', ')}
WHERE ${wherePairs.map(([key]) => `${key} = ?`).join(' AND ')}
`;
const stmt = this.db.prepare(sql);
const result = stmt.run(...updateValues, ...whereValues);
return result.changes;
}
/**
* Deletes entities matching the specified condition
* @param whereCondition WHERE condition
* @returns Number of deleted rows
*/
delete(whereCondition) {
const wherePairs = Object.entries(whereCondition);
if (wherePairs.length === 0) {
throw new Error('Delete operation requires a condition');
}
const whereValues = wherePairs.map(p => p[1]);
const sql = `
DELETE FROM ${this.tableInfo.name}
WHERE ${wherePairs.map(([key]) => `${key} = ?`).join(' AND ')}
`;
const stmt = this.db.prepare(sql);
const result = stmt.run(...whereValues);
return result.changes;
}
/**
* Deletes an entity by its ID
* @param id Entity ID
* @returns Number of deleted rows
*/
deleteById(id) {
const primaryKey = this.tableInfo.primaryKey || 'id';
return this.delete({ [primaryKey]: id });
}
/**
* Executes a custom SQL query
* @param sql SQL statement
* @param params Query parameters
* @returns Query results
*/
query(sql, params = []) {
const stmt = this.db.prepare(sql);
return stmt.all(...params);
}
/**
* Executes a custom SQL statement
* @param sql SQL statement
* @param params Statement parameters
* @returns Statement result
*/
execute(sql, params = []) {
const stmt = this.db.prepare(sql);
return stmt.run(...params);
}
}
exports.BaseService = BaseService;
//# sourceMappingURL=BaseService.js.map