add api route
This commit is contained in:
parent
334fce3b9b
commit
2247b18cda
47
libs/route-utils/index.js
Normal file
47
libs/route-utils/index.js
Normal file
@ -0,0 +1,47 @@
|
||||
/**
|
||||
* check Object
|
||||
* @param {string} key key name
|
||||
* @param {string} type type name
|
||||
* @param {boolean} empty can empty
|
||||
*/
|
||||
const chkObject = 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 this.body)) return false
|
||||
|
||||
switch (type) {
|
||||
case 'string':
|
||||
if (typeof this.body[key] !== 'string' || (!empty && !this.body[key])) return false
|
||||
break
|
||||
case 'number':
|
||||
if (!isFinite(this.body[key])) return false
|
||||
break
|
||||
case 'boolean':
|
||||
if (typeof this.body[key] !== 'boolean') return false
|
||||
break
|
||||
case 'array':
|
||||
if (!Array.isArray(this.body[key]) || (!empty && this.body[key].length === 0)) return false
|
||||
break
|
||||
case 'uuid':
|
||||
if (typeof this.body[key] !== 'string') return false
|
||||
if (!empty && this.body[key] === '') return false
|
||||
if (!empty && !uuidChk.test(this.body[key])) return false
|
||||
break
|
||||
case 'object':
|
||||
if (typeof this.body[key] !== 'object') return false
|
||||
try {
|
||||
let str = JSON.stringify(this.body[key])
|
||||
JSON.parse(str)
|
||||
} catch (err) {
|
||||
return false
|
||||
}
|
||||
break
|
||||
default:
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
chkObject
|
||||
}
|
@ -1,4 +1,22 @@
|
||||
const Router = require('koa-router')
|
||||
const koaBody = require('koa-body')
|
||||
const {
|
||||
chkObject
|
||||
} = require('@libs/route-utils')
|
||||
const r = new Router()
|
||||
|
||||
r.use(async (c, n) => {
|
||||
c.obj = {}
|
||||
c.chkBody = chkObject.bind({body: c.request.body})
|
||||
try {
|
||||
await n()
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
}
|
||||
})
|
||||
|
||||
r.post('/login', koaBody(), async (c, n) => {
|
||||
|
||||
})
|
||||
|
||||
module.exports = r
|
||||
|
Loading…
Reference in New Issue
Block a user