forked from ttc/micro-service-api
44 lines
1.5 KiB
JavaScript
44 lines
1.5 KiB
JavaScript
|
|
/**
|
||
|
|
* 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]'
|
||
|
|
}
|
||
|
|
}
|