Files
P42_API/p42ApiEndpoints.js
2026-06-13 14:21:20 +00:00

62 lines
1.8 KiB
JavaScript

import { Utils } from './helpers/utils.js'
import { MySQLClient } from './helpers/mysqlClient.js'
import { apiMethods, apiMappings } from './api/index.js'
export class P42ApiEndpoints{
constructor(app, db) {
this.db = new MySQLClient(db, 60)
this.app = app
this.utils = new Utils()
Object.assign(this, apiMethods)
this.registerPaths()
}
registerPaths(){
for(const apiEntry of apiMappings){
this.app[apiEntry.method](apiEntry.url, apiEntry.middlewares, this[apiEntry.handler].bind(this))
}
}
err(req, res, msg, debug, status=500) {
if(!debug) debug = msg
let jsonResp = {'success':false,
'payload': null,
'error': {
'displayMessage' : msg,
'debugMessage' : debug
}
}
res.set('Content-Type', 'application/json');
res.status(status)
res.send(JSON.stringify(jsonResp));
}
ok(req, res, payload) {
let jsonResp = { "success": true,
"payload": payload,
};
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(jsonResp));
}
async makeSession(req, res) {
req.session.userinfo = req.body
console.log('REQ body:', req.body)
this.ok(req, res, {})
}
hasRole(req, roles) {
const userRoles = req.session?.userInfos?.roles
if(!userRoles) return(false)
if(typeof(roles) == 'string') return(userRoles.includes(roles))
else if(Array.isArray(roles)) {
for(let role of roles) {
if(userRoles.includes(role)) return(true)
}
}
return(false)
}
}