70 lines
1.5 KiB
JavaScript
70 lines
1.5 KiB
JavaScript
import knex from 'knex';
|
|
import 'dotenv/config';
|
|
import executeJsonQuery from './jsonQueryExecutor.js';
|
|
|
|
/**
|
|
* Knex configuration
|
|
* Uses environment variables with sane defaults
|
|
*/
|
|
const config = {
|
|
client: 'pg',
|
|
connection: {
|
|
host: process.env.PGHOST || '127.0.0.1',
|
|
port: Number(process.env.PGPORT || 5432),
|
|
user: process.env.PGUSER || 'postgres',
|
|
password: process.env.PGPASSWORD || 'postgres',
|
|
database: process.env.PGDATABASE || 'postgres',
|
|
},
|
|
pool: {
|
|
min: 2,
|
|
max: 10,
|
|
},
|
|
};
|
|
|
|
const knexInstance = knex(config);
|
|
|
|
const dbClient = {
|
|
|
|
async execute(query) {
|
|
if (!query || typeof query !== 'object') {
|
|
throw new Error('Invalid query object');
|
|
}
|
|
|
|
switch (query.type) {
|
|
|
|
case 'json': {
|
|
return await executeJsonQuery(knexInstance, query);
|
|
}
|
|
|
|
case 'raw-builder': {
|
|
if (typeof query.handler !== 'function') {
|
|
throw new Error('raw-builder requires a handler function');
|
|
}
|
|
return await query.handler(knexInstance);
|
|
}
|
|
|
|
case 'transaction': {
|
|
if (typeof query.handler !== 'function') {
|
|
throw new Error('transaction requires a handler function');
|
|
}
|
|
|
|
return await knexInstance.transaction(async (trx) => {
|
|
return await query.handler(trx);
|
|
});
|
|
}
|
|
|
|
default:
|
|
throw new Error(`Unsupported query type: ${query.type}`);
|
|
}
|
|
},
|
|
|
|
getKnex() {
|
|
return knexInstance;
|
|
},
|
|
|
|
async destroy() {
|
|
await knexInstance.destroy();
|
|
}
|
|
};
|
|
|
|
export default dbClient; |