From 3c92bb8e6b93c0f65ecc30014850754ba0911a33 Mon Sep 17 00:00:00 2001 From: xxeol Date: Thu, 13 Jan 2022 02:19:01 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=8A=B5=EA=B4=80=EB=B0=A9=20detail=20?= =?UTF-8?q?GET=20api?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- functions/api/routes/auth/index.js | 3 +- functions/api/routes/room/index.js | 1 + functions/api/routes/room/roomDetailGET.js | 126 +++++++++++++++++++++ functions/constants/responseMessage.js | 3 + functions/db/index.js | 1 + functions/db/room.js | 36 +++++- functions/db/spark.js | 17 +++ functions/package.json | 2 +- 8 files changed, 185 insertions(+), 4 deletions(-) create mode 100644 functions/api/routes/room/roomDetailGET.js create mode 100644 functions/db/spark.js diff --git a/functions/api/routes/auth/index.js b/functions/api/routes/auth/index.js index 86bb179..e7a0c8a 100644 --- a/functions/api/routes/auth/index.js +++ b/functions/api/routes/auth/index.js @@ -4,7 +4,6 @@ const uploadImage = require('../../../middlewares/uploadImage'); const { checkUser } = require('../../../middlewares/auth'); router.post('/signup',uploadImage, require('./authSignupPOST')); -// router.get('/test', checkUser, require('./authTestGET')); router.get('/test', checkUser, require('./authTestGET')); -module.exports = router; +module.exports = router; \ No newline at end of file diff --git a/functions/api/routes/room/index.js b/functions/api/routes/room/index.js index 9057b23..6e38c4e 100644 --- a/functions/api/routes/room/index.js +++ b/functions/api/routes/room/index.js @@ -4,5 +4,6 @@ const { checkUser } = require('../../../middlewares/auth'); router.get('/code/:code', checkUser, require('./roomCodeGET')); router.post('', checkUser, require('./roomPOST')); +router.get('/:roomId', checkUser, require('./roomDetailGET')); module.exports = router; diff --git a/functions/api/routes/room/roomDetailGET.js b/functions/api/routes/room/roomDetailGET.js new file mode 100644 index 0000000..fb3c335 --- /dev/null +++ b/functions/api/routes/room/roomDetailGET.js @@ -0,0 +1,126 @@ +const functions = require('firebase-functions'); +const admin = require('firebase-admin'); +const util = require('../../../lib/util'); +const statusCode = require('../../../constants/statusCode'); +const responseMessage = require('../../../constants/responseMessage'); +const db = require('../../../db/db'); +const { userDB, roomDB, sparkDB } = require('../../../db'); +const jwtHandlers = require('../../../lib/jwtHandlers'); +const slackAPI = require('../../../middlewares/slackAPI'); +const dayjs = require('dayjs'); +const timezone = require('dayjs/plugin/timezone'); +const utc = require('dayjs/plugin/utc'); + + +/** + * @습관방_상세_조회 + * @route GET /room/:roomId + * @error + * 1. 존재하지 않는 습관방인 경우 + * 2. 진행중인 습관방이 아닌 경우 + * 3. 접근 권한이 없는 유저인 경우 + */ + +module.exports = async (req, res) => { + const { roomId } = req.params; + const user = req.user; + + let client; + dayjs.extend(utc); + dayjs.extend(timezone); + + try { + client = await db.connect(req); + + const room = await roomDB.getRoomById(client, roomId); + // console.log("room:", room); + + const startDate = dayjs(room.startAt); + const endDate = dayjs(room.endAt); + const now = dayjs().add(9, "hour"); + const today = dayjs(now.format("YYYY-MM-DD")); + const leftDay = endDate.diff(today, "day"); + const day = today.diff(startDate,"day") + 1; + + // console.log("start\n", startDate); + // console.log("today\n", today, today.diff(startDate,"day")); + // console.log("now\n", now, now.diff(startDate,"day")); + // console.log("day\n", day); + // console.log("leftDay\n", leftDay); + + // @error 1. 존재하지 않는 습관방인 경우 + if (!room) { + res.status(statusCode.NO_CONTENT).send(util.fail(statusCode.NO_CONTENT, responseMessage.GET_ROOM_DATA_FAIL)); + } + // @error 2. 진행중인 습관방이 아닌 경우 + if (!room.isStarted || leftDay < 0) { + res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.BAD_REQUEST, responseMessage.NOT_ONGOING_ROOM)); + } + const entries = await roomDB.getEntriesByRoomId(client, roomId); + + // @error 3. 접근 권한이 없는 유저인 경우 + const userEntry = entries.filter((entry) => entry.userId === user.userId); + // console.log(userEntry); + if (!userEntry.length) { + res.status(statusCode.UNAUTHORIZED).send(util.fail(statusCode.UNAUTHORIZED, responseMessage.NOT_MEMBER)); + } + + const records = await roomDB.getRecordsByDay(client, roomId, day); + + let myRecord = null; + + let otherRecords = []; + records.map((record) => { + if (record.userId === user.userId) { + myRecord = { + recordId: record.recordId, + userId: record.userId, + profileImg: record.profileImg, + nickname: record.nickname, + status: record.status, + rest: record.rest + } + } + else{ + otherRecords.push({ + recordId: record.recordId, + userId: record.userId, + profileImg: record.profileImg, + nickname: record.nickname, + status: record.status + }); + } + }); + + const recievedSpark = await sparkDB.countSparkByRecordId(client, myRecord.recordId); + myRecord.recievedSpark = parseInt(recievedSpark[0].count); + + console.log("myRecrod", myRecord); + console.log("otherRecords", otherRecords); + + const data = { + roomId, + roomName: room.roomName, + startDate: startDate.format('YYYY.MM.DD.'), + endDate: endDate.format('YYYY.MM.DD.'), + moment: userEntry.moment, + purpose: userEntry.purpose, + leftDay, + life: room.life, + fromStart: room.fromStart, + myRecord, + otherRecords + } + + res.status(statusCode.OK).send(util.success(statusCode.OK, responseMessage.GET_ROOM_DETAIL_SUCCESS, data)); + + } catch (error) { + console.log(error); + functions.logger.error(`[ERROR] [${req.method.toUpperCase()}] ${req.originalUrl}`, `[CONTENT] ${error}`); + const slackMessage = `[ERROR] [${req.method.toUpperCase()}] ${req.originalUrl} ${error} ${JSON.stringify(error)}`; + slackAPI.sendMessageToSlack(slackMessage, slackAPI.DEV_WEB_HOOK_ERROR_MONITORING); + res.status(statusCode.INTERNAL_SERVER_ERROR).send(util.fail(statusCode.INTERNAL_SERVER_ERROR, responseMessage.INTERNAL_SERVER_ERROR)); + } finally { + client.release(); + } +}; \ No newline at end of file diff --git a/functions/constants/responseMessage.js b/functions/constants/responseMessage.js index 01f2b57..ded791a 100644 --- a/functions/constants/responseMessage.js +++ b/functions/constants/responseMessage.js @@ -28,4 +28,7 @@ module.exports = { GET_WAITROOM_DATA_ALREADY: '이미 사용자가 참가중인 방입니다', GET_WAITROOM_DATA_FAIL: '대기방 정보 확인 실패', GET_WAITROOM_DATA_KICKED: '습관 방 생성자에 의해 내보내진 방입니다', + GET_ROOM_DATA_FAIL: '존재하지 않는 습관방입니다', + NOT_ONGOING_ROOM: '현재 진행중인 습관방이 아닙니다', + NOT_MEMBER: '참여중인 습관방이 아닙니다', }; diff --git a/functions/db/index.js b/functions/db/index.js index 955d655..24a14f8 100644 --- a/functions/db/index.js +++ b/functions/db/index.js @@ -1,4 +1,5 @@ module.exports = { userDB: require('./user'), roomDB: require('./room'), + sparkDB: require('./spark'), }; diff --git a/functions/db/room.js b/functions/db/room.js index e4c466e..4f75696 100644 --- a/functions/db/room.js +++ b/functions/db/room.js @@ -42,6 +42,18 @@ const getRoomByCode = async (client, code) => { return convertSnakeToCamel.keysToCamel(rows[0]); }; +const getRoomById = async (client, roomId) => { + const { rows } = await client.query( + ` + SELECT * FROM spark.room + WHERE room_id = $1 + AND is_deleted = FALSE + `, + [roomId], + ); + return convertSnakeToCamel.keysToCamel(rows[0]); +}; + const getEntriesByRoomId = async (client, roomId) => { const { rows } = await client.query( ` @@ -57,6 +69,7 @@ const getEntriesByRoomId = async (client, roomId) => { return convertSnakeToCamel.keysToCamel(rows); }; + const checkKickedByRoomIdAndUserId = async (client, roomId, userId) => { const { rows } = await client.query( ` @@ -71,4 +84,25 @@ const checkKickedByRoomIdAndUserId = async (client, roomId, userId) => { return convertSnakeToCamel.keysToCamel(rows); }; -module.exports = { addRoom, isCodeUnique, getRoomByCode, getEntriesByRoomId, checkKickedByRoomIdAndUserId }; +const getRecordsByDay = async (client, roomId, day) => { + const { rows } = await client.query( + ` + SELECT * FROM spark.entry e + INNER JOIN spark.record r + ON r.entry_id = e.entry_id + INNER JOIN spark.user u + ON e.user_id = u.user_id + WHERE e.room_id = $1 + AND e.is_out = FALSE + AND e.is_kicked = FALSE + AND e.is_deleted = FALSE + AND r.is_deleted = FALSE + AND r.day = $2 + ORDER BY e.created_at + `, + [roomId,day] + ); + return convertSnakeToCamel.keysToCamel(rows); +}; + +module.exports = { addRoom, isCodeUnique, getRoomById, getRoomByCode, getEntriesByRoomId, checkKickedByRoomIdAndUserId, getRecordsByDay }; \ No newline at end of file diff --git a/functions/db/spark.js b/functions/db/spark.js new file mode 100644 index 0000000..a2f4bb6 --- /dev/null +++ b/functions/db/spark.js @@ -0,0 +1,17 @@ +const _ = require('lodash'); +const convertSnakeToCamel = require('../lib/convertSnakeToCamel'); + +const countSparkByRecordId = async (client, recordId) => { + const { rows } = await client.query( + ` + SELECT COUNT(*) + FROM spark.spark + WHERE record_id = $1 + `, + [recordId], + ); + return convertSnakeToCamel.keysToCamel(rows); + }; + +module.exports = { countSparkByRecordId }; + diff --git a/functions/package.json b/functions/package.json index 1b7fb07..90d7c8f 100644 --- a/functions/package.json +++ b/functions/package.json @@ -28,10 +28,10 @@ "firebase-functions": "^3.11.0", "helmet": "^4.6.0", "hpp": "^0.2.3", - "nanoid": "^3.1.30", "jsonwebtoken": "^8.5.1", "lodash": "^4.17.21", "multer": "^1.4.3", + "nanoid": "^3.1.30", "pg": "^8.7.1" }, "devDependencies": {