forked from ttc/micro-service-api
-first commit
This commit is contained in:
43
exthernal-accountingwep-api/src/utils/response.js
Normal file
43
exthernal-accountingwep-api/src/utils/response.js
Normal file
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* sendResponse
|
||||
* ----------------------------------------------
|
||||
* ส่ง response แบบมาตรฐาน รองรับข้อความ 2 ภาษา
|
||||
* ----------------------------------------------
|
||||
* @param {object} res - Express response object
|
||||
* @param {number} status - HTTP Status code (200, 400, 500, etc.)
|
||||
* @param {string} msg_th - ข้อความภาษาไทย
|
||||
* @param {string} msg_en - ข้อความภาษาอังกฤษ
|
||||
* @param {any} [data=null] - optional data
|
||||
*/
|
||||
|
||||
// ===================================================
|
||||
// 🧩 Unified Response Handler (vFinal+)
|
||||
// ===================================================
|
||||
// ===================================================
|
||||
// 📁 src/utils/response.js
|
||||
// ===================================================
|
||||
export function sendResponse(res, status, msg_th = null, msg_en = null, data = null) {
|
||||
const safeData = safeJson(data)
|
||||
const success = status < 400
|
||||
const response = {
|
||||
status: success ? 'succeed' : 'error',
|
||||
message: {
|
||||
th: msg_th ?? (success ? 'สำเร็จ' : 'เกิดข้อผิดพลาด'),
|
||||
en: msg_en ?? (success ? 'Succeed' : 'Error')
|
||||
},
|
||||
data: safeData
|
||||
}
|
||||
res.status(status).json(response)
|
||||
}
|
||||
|
||||
// ✅ ป้องกัน circular reference
|
||||
function safeJson(obj) {
|
||||
try {
|
||||
if (obj && typeof obj === 'object') {
|
||||
return JSON.parse(JSON.stringify(obj))
|
||||
}
|
||||
return obj
|
||||
} catch (err) {
|
||||
return '[Unserializable Object]'
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user