72 lines
1.7 KiB
JavaScript
72 lines
1.7 KiB
JavaScript
const Router = require('koa-router')
|
|
const router = new Router()
|
|
const koaBody = require('koa-body')
|
|
|
|
// import tools
|
|
const mysql = require('../../libs/mysql_pool.js')
|
|
// const so = require('../../libs/storeObject')
|
|
// const config = require('../../config.json')
|
|
const msgMng = require('./MsgManager')
|
|
|
|
// routes
|
|
const accountApi = require('./account.js')
|
|
|
|
// api response handler
|
|
router.use(async(c, n) => {
|
|
// get MySQL connection
|
|
c.db = await mysql.getConn()
|
|
// set Async/Await Query
|
|
c.syncQuery = (query, param = null) => {
|
|
return new Promise((resolve, reject) => {
|
|
if (param != null) {
|
|
c.db.query(query, param, (err, row) => {
|
|
if (err) return reject(err)
|
|
return resolve(row)
|
|
})
|
|
} else {
|
|
c.db.query(query, (err, row) => {
|
|
if (err) return reject(err)
|
|
return resolve(row)
|
|
})
|
|
}
|
|
})
|
|
}
|
|
c.token = c.headers['x-auth-token'] || ''
|
|
|
|
try {
|
|
await n()
|
|
c.body = {
|
|
data: c.body,
|
|
status: 1
|
|
}
|
|
} catch (e) {
|
|
let msg = msgMng.getMsg(e, c.headers['accept-language'])
|
|
c.body = {
|
|
errorCode: e,
|
|
message: msg,
|
|
servErr: c.serr ? c.serr.toString() : '',
|
|
status: 0
|
|
}
|
|
if (e[0] === 'C' || e[0] === 'c') c.status = 400
|
|
if (e[0] === 'S' || e[0] === 's') c.status = 500
|
|
}
|
|
if ('db' in c && typeof c.db === 'object' && 'release' in c.db && typeof c.db.release === 'function') c.db.release()
|
|
})
|
|
|
|
// enable bodyParser
|
|
router.all('*', koaBody({
|
|
multipart: true,
|
|
// upload file size 10mb
|
|
maxFieldSize: 10 * 1024 * 1024
|
|
}), async(c, n) => { await n() })
|
|
|
|
router
|
|
.get('/', async(c, n) => {
|
|
c.body = {
|
|
msg: 'API Endpoint'
|
|
}
|
|
})
|
|
.use('/account', accountApi.routes())
|
|
|
|
module.exports = router
|