add get line msg log api

This commit is contained in:
Jay 2018-09-15 17:35:39 +08:00
parent 45271196bf
commit d4918b467f
2 changed files with 74 additions and 2 deletions

View File

@ -134,11 +134,51 @@ const checkSession = async (c, n) => {
return n() return n()
} }
/**
* @typedef pageobj
* @prop {number} totalPage
* @prop {number} offset
* @prop {number} limit
* @prop {number} page
*/
/**
* calculate page object
* @param {number} count data row count
* @param {number} page page
* @param {number} maxItem page show item limit
* @return {pageobj}
*/
const calPage = function (count, page, maxItem = 10) {
if (!count || !isFinite(count) || count < 0) count = 0
if (!page || !isFinite(page) || page < 1) page = 1
if (!maxItem || !isFinite(maxItem) || maxItem < 1) maxItem = 10
let totalPage = Math.ceil(count / maxItem)
if (totalPage < 1) totalPage = 1
if (page > totalPage) page = totalPage
let offset = (page - 1) * maxItem
if (offset > count) offset = count
let limit = maxItem
totalPage = toInt(totalPage)
offset = toInt(offset)
limit = toInt(limit)
page = toInt(page)
return {
totalPage,
offset,
limit,
page
}
}
module.exports = { module.exports = {
chkObject, chkObject,
resObject, resObject,
toInt, toInt,
APIError, APIError,
genError, genError,
checkSession checkSession,
calPage
} }

View File

@ -5,7 +5,9 @@ const {
resObject, resObject,
APIError, APIError,
genError, genError,
checkSession checkSession,
calPage,
toInt
} = require('@libs/route-utils') } = require('@libs/route-utils')
const DB = require('@libs/database') const DB = require('@libs/database')
const r = new Router() const r = new Router()
@ -67,6 +69,36 @@ r.get('/session', checkSession, async (c, n) => {
}) })
}) })
r.get('/line_msg', checkSession, async (c, n) => {
let p = toInt(c.query.p, 1, 1)
let text = `select count(*) as c from "public"."line_message_log"`
let msgCount = await c.db.query({text})
if (msgCount.rowCount === 0) throw genError('InternalError', 'database query fail')
if (!('c' in msgCount.rows[0])) throw genError('InternalError', 'database query fail')
let page = calPage(msgCount.rows[0].c, p, 20)
text = `select g.name, u.name as user, m.message, m.ctime from "public"."line_message_log" m
left join "public"."line_group" g
on g.id = m.group
left join "public"."line_user" u
on u.id = m.user
order by m.ctime desc
offset $1
limit $2`
let values = [page.offset, page.limit]
let msgData = await c.db.query({
text,
values
})
c.obj = resObject('Success', {
messages: msgData.rows,
page: {
cur: page.page,
total: page.totalPage
}
})
})
r.use('/twitch', require('./twitch').routes()) r.use('/twitch', require('./twitch').routes())
module.exports = r module.exports = r