2018-06-25 10:07:10 +00:00
|
|
|
const Router = require('koa-router')
|
|
|
|
const r = new Router()
|
|
|
|
// const koaBody = require('koa-body')
|
|
|
|
const rawBody = require('raw-body')
|
|
|
|
const {
|
|
|
|
verifyLine
|
|
|
|
} = require('../../libs/middleware')
|
2018-06-26 10:04:19 +00:00
|
|
|
const {
|
|
|
|
textMessage
|
|
|
|
} = require('../../libs/line-message')
|
2018-06-25 10:07:10 +00:00
|
|
|
|
|
|
|
const getRaw = async (c, n) => {
|
|
|
|
let raw = await rawBody(c.req, {
|
|
|
|
length: c.request.length,
|
|
|
|
limit: '5mb',
|
|
|
|
encoding: c.request.charset
|
|
|
|
})
|
|
|
|
c.request.raw = raw
|
|
|
|
let txt = raw instanceof Buffer ? raw.toString() : raw
|
|
|
|
if (c.request.type === 'application/json') {
|
|
|
|
try {
|
|
|
|
c.request.body = JSON.parse(txt)
|
|
|
|
} catch (err) {
|
|
|
|
c.request.body = txt
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return n()
|
|
|
|
}
|
|
|
|
|
|
|
|
r.post('/', getRaw, verifyLine, async (c, n) => {
|
2018-06-26 10:04:19 +00:00
|
|
|
console.log(JSON.stringify(c.request.body, null, 2))
|
|
|
|
if (!('events' in c.request.body)) return c.throw(400, 'data struct error')
|
|
|
|
let evt = c.request.body.events || []
|
|
|
|
evt.forEach(t => {
|
|
|
|
let type = t.type
|
|
|
|
switch (type) {
|
|
|
|
case 'message':
|
|
|
|
textMessage(t).catch(err => {
|
|
|
|
console.log(err)
|
|
|
|
})
|
|
|
|
break
|
|
|
|
}
|
|
|
|
})
|
2018-06-25 10:07:10 +00:00
|
|
|
c.body = 'success'
|
|
|
|
c.status = 200
|
|
|
|
})
|
|
|
|
|
|
|
|
module.exports = r
|