webio-node/route/api/index.js

59 lines
1.9 KiB
JavaScript

const express = require('express');
const router = express.Router();
const errMng = require('../../includes/errorManager');
const so = require('../../includes/storeObject');
const mysql = require('../../libs/mysql_pool');
router
.get('/', (req, res) => {
res.send({ name: 'WebIO API System' });
})
.all('*', async(req,res,n)=>{
if('x-auth-token' in req.headers) {
let token = req.headers['x-auth-token'];
if(so.chkKey(token)){
let obj = so.get(token);
if(obj != null) {
so.set(token, obj);
}
}
}
try{
res.db = await mysql.getConn();
}catch(e){
return n('ERR8100');
}
n();
})
.get('/showallso', (req,res)=>{
res.send(so.show());
})
.use('/system', require('./system.js'))
.use('/log', require('./log.js'))
.use('/leone', require('./leone.js'))
.use('/iogroup', require('./iogroup.js'))
.use('/iocmd', require('./iocmd.js'))
.use('/schedule', require('./schedule.js'))
.use('/dio', require('./dio.js'))
.use('/link', require('./link.js'))
.use('/modbus', require('./modbus.js'))
.use('/ipcam', require('./ipcam.js'));
// api error handler
router.use((err, req, res, n) => {
if ('db' in res && typeof res.db == 'object' && 'close' in res.db && typeof res.db.close == 'function') res.db.close();
if ('db' in res && typeof res.db == 'object' && 'release' in res.db && typeof res.db.release == 'function') res.db.release();
let lngs = req.headers['accept-language'].split(',');
let lng = null;
if (lngs.length > 0) {
lng = lngs[0].substring(0, 2);
}
res.send({
errorCode: (typeof err != 'string' ? err.toString() : err),
message: errMng(err, lng),
status: 0
});
})
module.exports = router;