63 lines
1.6 KiB
JavaScript
63 lines
1.6 KiB
JavaScript
const Router = require('koa-router')
|
|
const r = new Router()
|
|
const {
|
|
resObject,
|
|
MError
|
|
} = require('../utils')
|
|
|
|
r.use(async(c, n) => {
|
|
c.obj = c.obj || {}
|
|
c.chkBody = function (key = '', type = '', empty = false) {
|
|
const uuidChk = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
|
|
if (!(key in c.request.body)) return false
|
|
|
|
switch (type) {
|
|
case 'string':
|
|
if (typeof c.request.body[key] !== 'string' || (!empty && !c.request.body[key])) return false
|
|
break
|
|
case 'number':
|
|
if (!isFinite(c.request.body[key])) return false
|
|
break
|
|
case 'boolean':
|
|
if (typeof c.request.body[key] !== 'boolean') return false
|
|
break
|
|
case 'array':
|
|
if (!Array.isArray(c.request.body[key]) || (!empty && c.request.body[key].length === 0)) return false
|
|
break
|
|
case 'uuid':
|
|
if (typeof c.request.body[key] !== 'string') return false
|
|
if (!empty && c.request.body[key] === '') return false
|
|
if (!empty && !uuidChk.test(c.request.body[key])) return false
|
|
break
|
|
default:
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
let obj = null
|
|
try {
|
|
await n()
|
|
} catch (e) {
|
|
console.log(e)
|
|
obj = resObject(e instanceof MError ? e.mtype : 'InternalError', e.msg || '')
|
|
}
|
|
|
|
if (Object.keys(c.obj).length > 0 && 'status' in c.obj && 'obj' in c.obj) {
|
|
c.status = c.obj.status
|
|
c.body = c.obj.obj
|
|
}
|
|
|
|
if (obj !== null) {
|
|
c.status = obj.status
|
|
c.body = obj.obj
|
|
}
|
|
})
|
|
|
|
r.get('/', async (c, n) => {
|
|
c.obj = resObject('Success')
|
|
})
|
|
|
|
module.exports = r
|