forked from ttc/micro-service-api
-web-service
This commit is contained in:
@@ -1,43 +1,24 @@
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
// ===================================================
|
||||
// ⚙️ Nuttakit Response Layer vFinal++++++
|
||||
// ===================================================
|
||||
|
||||
// ===================================================
|
||||
// 🧩 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]'
|
||||
export function sendError(thMsg = 'เกิดข้อผิดพลาดไม่คาดคิดเกิดขึ้น', enMsg = 'Unexpected error', code = 400) {
|
||||
return {
|
||||
code: String(code),
|
||||
message: enMsg,
|
||||
message_th: thMsg,
|
||||
data: []
|
||||
}
|
||||
}
|
||||
|
||||
// ===================================================
|
||||
// 🔹 Auto Success Response (ใช้โดย Global Handler เท่านั้น)
|
||||
// ===================================================
|
||||
export function formatSuccessResponse(data) {
|
||||
return {
|
||||
code: "200",
|
||||
message: "successful",
|
||||
message_th: "ดำเนินการสำเร็จ",
|
||||
data: data || null
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user