--ระบบ ที่สมบูรของ search column และ condition

This commit is contained in:
2025-11-17 15:38:58 +07:00
parent da081dd457
commit a0295a160c
3 changed files with 18 additions and 6 deletions

View File

@@ -22,6 +22,7 @@ export class budgetSearch {
async onBudgetSearch(req, res, database) {
let idx = -1
let aryResult = []
let condition = {}
try {
// let username = req.body.request.username;
// let password = req.body.request.password;
@@ -35,16 +36,18 @@ export class budgetSearch {
var column = ""
if(columnParams == 'edit'){
column = `bdgseq, bdgnam, bdgcod, bdgttl`
condition['bdgseq'] = req.body.request.bdgseq
} else if(columnParams == 'result' || columnParams == undefined || columnParams == ''){
column = `bdgnam, bdgttl`
}
aryResult = await this.budgetSearchService.getBudgetSearch(database, id, column);
aryResult = await this.budgetSearchService.getBudgetSearch(database, id, column, condition);
} catch (error) {
idx = 1;
} finally {
if (idx === 1) return sendError('เกิดข้อผิดพลาดไม่คาดคิดเกิดขึ้น', 'Unexpected error');
if (!aryResult) return sendError('ไม่พบการมีอยู่ของข้อมูล', 'Cannot Find Any Data');
if (aryResult == 0) return sendError('ไม่พบการมีอยู่ของข้อมูล', 'Cannot Find Any Data');
return aryResult
}
}

View File

@@ -6,14 +6,15 @@ export class BudgetSearchService {
this.generalService = new GeneralService()
}
async getBudgetSearch(database, id, column) {
async getBudgetSearch(database, id, column, condition) {
const sql = `
SELECT
${column}
FROM ${database}.bdgmst
WHERE 1=1
`
const params = []
const result = await this.generalService.executeQueryParam(database, sql, params);
const result = await this.generalService.executeQueryConditions(database, sql, condition);
return result
}
}

View File

@@ -54,7 +54,9 @@ export class GeneralService {
for (const [key, value] of Object.entries(conditions)) {
if (value === undefined || value === null || value === '') continue
const match = String(value).match(/^(ILIKE|LIKE)\s+(.+)$/i)
if (match) {
const operator = match[1].toUpperCase()
const pattern = match[2].trim()
@@ -69,6 +71,7 @@ export class GeneralService {
let finalQuery = baseQuery
if (whereClauses.length > 0) finalQuery += ' AND ' + whereClauses.join(' AND ')
const formattedSQL = finalQuery.replace(/\${database}/g, database)
try {
@@ -77,15 +80,20 @@ export class GeneralService {
sql: formattedSQL,
params
})
const result = await connection.query(formattedSQL, params)
this.devhint(2, 'executeQueryConditions', `✅ Query Success (${result.rowCount} rows)`)
return result.rows
return result.rows
} catch (err) {
this.devhint(1, 'executeQueryConditions', `❌ SQL Error`, err.message)
console.error('🧨 SQL Error:', err.message)
throw new Error(`SQL_EXECUTION_FAILED::${err.message}`) // ✅ “เจ๊งจริง” ส่งถึง controller แน่นอน
throw new Error(`SQL_EXECUTION_FAILED::${err.message}`)
}
}
}
// ===================================================
// Export สำหรับ controller หรืออื่นๆ เรียกใช้ได้ด้วย