Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[GET] /room/:roomId 특정 습관방 조회 #31

Merged
merged 7 commits into from
Jan 13, 2022
3 changes: 1 addition & 2 deletions functions/api/routes/auth/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
1 change: 1 addition & 0 deletions functions/api/routes/room/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
126 changes: 126 additions & 0 deletions functions/api/routes/room/roomDetailGET.js
Original file line number Diff line number Diff line change
@@ -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);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여기서 utc, timezone을 extend 안해주면 작동하지 않는 dayjs 연산이 있을까요??!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"GET_ROOM_DETAIL_SUCCESS"
이 ResponseMessage 등록 안해주셨어요~~

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

앗! pull받으면서 삭제됐네요 추가할게요!!😀


} 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();
}
};
3 changes: 3 additions & 0 deletions functions/constants/responseMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: '참여중인 습관방이 아닙니다',
};
1 change: 1 addition & 0 deletions functions/db/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
module.exports = {
userDB: require('./user'),
roomDB: require('./room'),
sparkDB: require('./spark'),
};
36 changes: 35 additions & 1 deletion functions/db/room.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
`
Expand All @@ -57,6 +69,7 @@ const getEntriesByRoomId = async (client, roomId) => {
return convertSnakeToCamel.keysToCamel(rows);
};


const checkKickedByRoomIdAndUserId = async (client, roomId, userId) => {
const { rows } = await client.query(
`
Expand All @@ -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 };
17 changes: 17 additions & 0 deletions functions/db/spark.js
Original file line number Diff line number Diff line change
@@ -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 };

2 changes: 1 addition & 1 deletion functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down