From d4918b467f61c788244a3094fddb6fdd4bbacc8e Mon Sep 17 00:00:00 2001 From: jay Date: Sat, 15 Sep 2018 17:35:39 +0800 Subject: [PATCH] add get line msg log api --- libs/route-utils/index.js | 42 ++++++++++++++++++++++++++++++++++++++- route/api/index.js | 34 ++++++++++++++++++++++++++++++- 2 files changed, 74 insertions(+), 2 deletions(-) diff --git a/libs/route-utils/index.js b/libs/route-utils/index.js index c83aa01..1a62218 100644 --- a/libs/route-utils/index.js +++ b/libs/route-utils/index.js @@ -134,11 +134,51 @@ const checkSession = async (c, 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 = { chkObject, resObject, toInt, APIError, genError, - checkSession + checkSession, + calPage } diff --git a/route/api/index.js b/route/api/index.js index f21420f..0a199c6 100644 --- a/route/api/index.js +++ b/route/api/index.js @@ -5,7 +5,9 @@ const { resObject, APIError, genError, - checkSession + checkSession, + calPage, + toInt } = require('@libs/route-utils') const DB = require('@libs/database') 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()) module.exports = r