Skip to content

Commit

Permalink
Merge pull request #48 from TeamSparker/feature/#36
Browse files Browse the repository at this point in the history
[GET] /room?lastid=&size= 습관방 리스트 조회 api
  • Loading branch information
youngkwon02 authored Jan 15, 2022
2 parents 69d8849 + a0079b9 commit dcb9871
Show file tree
Hide file tree
Showing 7 changed files with 222 additions and 3 deletions.
1 change: 1 addition & 0 deletions functions/api/routes/room/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ router.post('/:roomId/enter', checkUser, require('./roomEnterPOST'));
router.patch('/:roomId/purpose', checkUser, require('./roomPurposePATCH'));
router.get('/:roomId/waiting', checkUser, require('./roomWaitingGET'));
router.get('/:roomId', checkUser, require('./roomDetailGET'));
router.get('', checkUser, require('./roomListGET'));
router.get('/:roomId/waiting/member', checkUser, require('./roomWaitingMemberGET'));
router.post('/:roomId/start', checkUser, require('./roomStartPOST'));

Expand Down
148 changes: 148 additions & 0 deletions functions/api/routes/room/roomListGET.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
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 { filter } = require('lodash');
const _ = require('lodash');
const roomPOST = require('./roomPOST');

/**
* @습관방_리스트_조회
* @route GET /room?lastid=&size=
* @error
* 1. 잘못된 lastid
*/

module.exports = async (req, res) => {
const lastid = Number(req.query.lastid);
const size = Number(req.query.size);
console.log(lastid, size);
const user = req.user;
console.log(user.userId);

let client;

try {
client = await db.connect(req);

const rawRooms = await roomDB.getRoomsByUserId(client, user.userId, ["NONE", "ONGOING"]);

const waitingRooms = rawRooms.filter((rawRoom) => rawRoom.status === "NONE");
const ongoingRooms = rawRooms.filter((rawRoom) => rawRoom.status === "ONGOING");

const waitingRoomIds = [...new Set(waitingRooms.filter(Boolean).map((room) => room.roomId))];
const ongoingRoomIds = [...new Set(ongoingRooms.filter(Boolean).map((room) => room.roomId))];
const roomIds = waitingRoomIds.concat(ongoingRoomIds);
let responseRoomIds = [];

// 최초 요청이 아닐시
if(lastid !== -1) {
const lastIndex = _.indexOf(roomIds, lastid);
// @error 1. 잘못된 last id
if (lastIndex === -1) {
return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.BAD_REQUEST, responseMessage.INVALID_LASTID));
}
responseRoomIds = roomIds.slice(lastIndex+1, lastIndex+1+size);
}
// 최초 요청시
else {
responseRoomIds = roomIds.slice(0, size);
}

console.log("responseRoomIds",responseRoomIds);

// 마지막일 때 -> 빈 배열 return
if(!responseRoomIds.length) {
res.status(statusCode.OK).send(util.success(statusCode.OK, responseMessage.GET_ROOM_LIST_SUCCESS, { "rooms": [] }));
}

const roomInfo = await roomDB.getRoomsByIds(client, responseRoomIds);

const today = dayjs(dayjs().add(9, 'hour').format('YYYY-MM-DD'));

// roomIds 빈 배열일 때 처리
const profiles = await roomDB.getUserProfilesByRoomIds(client, responseRoomIds, today);

// console.log(profiles);
let roomProfileImg = [];
let roomMemberNum = [];
let roomUserStatus = [];
let roomDoneMemberNum = [];
responseRoomIds.map((roomId) => {
const userStatus = profiles.filter(Boolean).filter((o) => {
if (o.roomId === roomId && o.userId === user.userId) {
return true;
}
return false;
});
if (userStatus === 'DONE') {
roomUserStatus.push(true);
}
else {
roomUserStatus.push(false);
}

const doneMembers = profiles.filter(Boolean).filter((o) => {
if (o.roomId === roomId && o.status === "DONE") {
return true;
}
return false;
});
roomDoneMemberNum.push(doneMembers.length);

let profileImgs = profiles.filter(Boolean).filter((o) => o.roomId === roomId).map((o) => o.profileImg);
roomMemberNum.push(profileImgs.length);
if(profileImgs.length < 3) {
console.log("length", profileImgs.length);
for(let i=0; i<3 - profileImgs.length; i++) {
profileImgs.push(null);
}
}
else {
profileImgs = profileImgs.slice(0,3);
}
roomProfileImg.push(profileImgs);
});

let rooms = [];
console.log("roomInfo", roomInfo);
for (let i=0; i<responseRoomIds.length ; i++) {

const endDate = dayjs(roomInfo[i].endAt);
const leftDay = endDate.diff(today, 'day');
let isStarted = true;
if (roomInfo[i] === 'NONE') {
isStarted = false;
}
const room = {
"roomId": roomInfo[i].roomId,
"roomName": roomInfo[i].roomName,
leftDay,
"profileImg": roomProfileImg[i],
"life": roomInfo[i].life,
isStarted,
"isDone": roomUserStatus[i],
"memberNum": roomMemberNum[i],
"doneMemberNum": roomDoneMemberNum[i]
}
rooms.push(room);
}

res.status(statusCode.OK).send(util.success(statusCode.OK, responseMessage.GET_ROOM_LIST_SUCCESS, { rooms }));

} 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();
}
};
2 changes: 2 additions & 0 deletions functions/constants/responseMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ module.exports = {
PATH_ERROR: '요청 경로가 올바르지 않습니다',
INTERNAL_SERVER_ERROR: '서버 내부 오류',
PRIV_NOT_FOUND: '권한이 없는 요청입니다',
INVALID_LASTID: '잘못된 lastid 입니다',

// 회원가입
CREATED_USER: '회원 가입 성공',
Expand Down Expand Up @@ -39,6 +40,7 @@ module.exports = {
GET_ROOM_DATA_FAIL: '존재하지 않는 습관방입니다',
NOT_ONGOING_ROOM: '현재 진행중인 습관방이 아닙니다',
NOT_MEMBER: '참여중인 습관방이 아닙니다',
GET_ROOM_LIST_SUCCESS: '참여중인 습관방 조회 완료',
START_ROOM_SUCCESS: '습관 방 시작 완료',
START_ROOM_ALREADY: '이미 시작된 방입니다',

Expand Down
9 changes: 8 additions & 1 deletion functions/db/notice.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,11 @@ const getActivesByUserId = async (client, userId, lastid, size) => {
return convertSnakeToCamel.keysToCamel(rows);
};

module.exports = { serviceReadByUserId, activeReadByUserId, getNoticeByNoticeId, deleteNoticeByNoticeId, getServicesByUserId, getActivesByUserId };
module.exports = {
serviceReadByUserId,
activeReadByUserId,
getNoticeByNoticeId,
deleteNoticeByNoticeId,
getServicesByUserId,
getActivesByUserId
};
53 changes: 53 additions & 0 deletions functions/db/room.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ const getRoomById = async (client, roomId) => {
return convertSnakeToCamel.keysToCamel(rows[0]);
};

const getRoomsByIds = async (client, roomIds) => {
const { rows } = await client.query(
`
SELECT * FROM spark.room
WHERE room_id IN (${roomIds.join()})
`,
);
return convertSnakeToCamel.keysToCamel(rows);
}

const getRoomByCode = async (client, code) => {
const { rows } = await client.query(
`
Expand All @@ -55,6 +65,23 @@ const getRoomByCode = async (client, code) => {
return convertSnakeToCamel.keysToCamel(rows[0]);
};

const getRoomsByUserId = async (client, userId) => {
const { rows } = await client.query(
`
SELECT * FROM spark.entry e
INNER JOIN spark.room r
ON r.room_id = e.room_id
WHERE e.user_id = $1
AND e.is_out = FALSE
AND e.is_kicked = FALSE
AND e.is_deleted = FALSE
ORDER BY r.start_at
`,
[userId],
);
return convertSnakeToCamel.keysToCamel(rows);
};

const getEntriesByRoomId = async (client, roomId) => {
const { rows } = await client.query(
`
Expand All @@ -70,6 +97,27 @@ const getEntriesByRoomId = async (client, roomId) => {
return convertSnakeToCamel.keysToCamel(rows);
};

const getUserProfilesByRoomIds = async (client, roomIds, today) => {
const { rows } = await client.query(
`
SELECT *
FROM spark.entry e
INNER JOIN spark.user u
ON u.user_id = e.user_id
LEFT JOIN spark.record r
ON e.entry_id = r.entry_id AND r.date = $1
WHERE e.room_id in (${roomIds.join()})
AND e.is_out = FALSE
AND e.is_kicked = FALSE
AND e.is_deleted = FALSE
AND u.is_deleted = FALSE
ORDER BY e.created_at
`,
[today]
);
return convertSnakeToCamel.keysToCamel(rows);
};

const kickedHistoryByIds = async (client, roomId, userId) => {
const { rows } = await client.query(
`
Expand All @@ -84,6 +132,7 @@ const kickedHistoryByIds = async (client, roomId, userId) => {
return convertSnakeToCamel.keysToCamel(rows);
};


const getEntryByIds = async (client, roomId, userId) => {
const { rows } = await client.query(
`
Expand Down Expand Up @@ -134,6 +183,7 @@ const getRecordsByDay = async (client, roomId, day) => {
return convertSnakeToCamel.keysToCamel(rows);
};


const checkEnteredById = async (client, roomId, userId) => {
const { rows } = await client.query(
`
Expand Down Expand Up @@ -235,8 +285,11 @@ module.exports = {
addRoom,
isCodeUnique,
getRoomById,
getRoomsByIds,
getRoomByCode,
getEntriesByRoomId,
getRoomsByUserId,
getUserProfilesByRoomIds,
kickedHistoryByIds,
getEntryByIds,
updatePurposeByEntryId,
Expand Down
4 changes: 3 additions & 1 deletion functions/db/spark.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,7 @@ const countSparkByRecordId = async (client, recordId) => {
return convertSnakeToCamel.keysToCamel(rows);
};

module.exports = { countSparkByRecordId };
module.exports = {
countSparkByRecordId
};

8 changes: 7 additions & 1 deletion functions/db/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,10 @@ const addUser = async (client, socialId, nickname, profileImg) => {
return convertSnakeToCamel.keysToCamel(rows[0]);
};

module.exports = { getAllUsers, getUserById, getUsersByIds, getUserBySocialId, addUser };
module.exports = {
getAllUsers,
getUserById,
getUsersByIds,
getUserBySocialId,
addUser
};

0 comments on commit dcb9871

Please sign in to comment.