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 errorMng = require('./errorManager'); // routes const user_api = require('./user.js'); // api response handler router.use(async (c, n) => { c.db = await mysql.getConn(); 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) }); } }) } // console.log(c.headers['accept-language']) try { await n(); c.body = { data: c.body, status: 1 } } catch (e) { let msg = errorMng.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(); // switch (typeof c.body) { // case 'undefined': // c.body = { errorCode: 'ERR9999', status: 0 }; // break; // case 'string': // c.body = { errorCode: c.body, status: 0 }; // break; // default: // c.body = { // data: c.body, // status: 1 // } // break; // } }) // 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('/user', user_api.routes()) module.exports = router;