forked from ttc/micro-service-api
62 lines
2.0 KiB
JavaScript
62 lines
2.0 KiB
JavaScript
import jwt from 'jsonwebtoken'
|
|
import { BdgmstInterface } from './table/bdgmstInterface.js'
|
|
import { PrjmstInterface } from './table/prjmstInterface.js'
|
|
import { TrnmstInterface } from './table/trnmstInterface.js'
|
|
import { sendError } from '../utils/response.js'
|
|
|
|
// import { ActmstInterface } from './actmstInterface.js'
|
|
|
|
// -------------------------------
|
|
// GLOBAL FILE
|
|
// -----------------------------
|
|
|
|
export class Interface {
|
|
|
|
constructor() {
|
|
this.map = {
|
|
bdgmst: new BdgmstInterface(),
|
|
prjmst: new PrjmstInterface(),
|
|
trnmst: new TrnmstInterface(),ห
|
|
// actmst: new ActmstInterface(),
|
|
}
|
|
}
|
|
|
|
// ===============================================================
|
|
// saveInterface → แกะ token เอง และ route ไปยัง interface เฉพาะ table
|
|
// ===============================================================
|
|
async saveInterface(tableName, data, req) {
|
|
|
|
// ------------------------------
|
|
// ✔ 1) จับ Interface ที่ตรงกับ table
|
|
// ------------------------------
|
|
const handler = this.map[tableName.toLowerCase()]
|
|
if (!handler) {
|
|
return new sendError(`Interface not found for table: ${tableName}`)
|
|
}
|
|
|
|
// ------------------------------
|
|
// ✔ 2) แกะ token → ดึง organization → schema
|
|
// ------------------------------
|
|
const token = req.headers.authorization?.split(' ')[1]
|
|
if (!token) {
|
|
return new sendError('ไม่พบการยืนยันตัวตน' ,'Missing token in request header')
|
|
}
|
|
|
|
let decoded
|
|
try {
|
|
decoded = jwt.verify(token, process.env.JWT_SECRET)
|
|
} catch (err) {
|
|
return new sendError('Invalid token: ' + err.message)
|
|
}
|
|
|
|
const schema = decoded.organization
|
|
if (!schema) return new sendError("Token missing 'organization' field")
|
|
|
|
// ------------------------------
|
|
// ✔ 3) ส่งงานไปยัง interface ของ table นั้น ๆ
|
|
// ------------------------------
|
|
return await handler.saveInterface(schema, data)
|
|
}
|
|
|
|
}
|