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] /myroom/:roomId 특정 습관방 사진 모아보기 #66

Merged
merged 7 commits into from
Jan 16, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion functions/api/routes/myroom/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const express = require('express');
const router = express.Router();
const { checkUser } = require('../../../middlewares/auth');

router.get('/:roomType', checkUser, require('./myroomGET'));
router.get('/:roomId', checkUser, require('./myroomRoomGET'));
router.get('', checkUser, require('./myroomGET'));

module.exports = router;
2 changes: 1 addition & 1 deletion functions/api/routes/myroom/myroomGET.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ const _ = require('lodash');
module.exports = async (req, res) => {
const lastid = Number(req.query.lastid);
const size = Number(req.query.size);
const roomType = req.query.type;
const user = req.user;
const { roomType } = req.params;

let client;

Expand Down
93 changes: 93 additions & 0 deletions functions/api/routes/myroom/myroomRoomGET.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
const functions = require('firebase-functions');
const admin = require('firebase-admin');
Copy link
Member

Choose a reason for hiding this comment

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

@xxeol2
설희쌤 요녀석 안쓰이는거 같아요~~

Copy link
Contributor Author

Choose a reason for hiding this comment

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

삭제했어요!

const util = require('../../../lib/util');
const statusCode = require('../../../constants/statusCode');
const responseMessage = require('../../../constants/responseMessage');
const db = require('../../../db/db');
const { userDB, roomDB, sparkDB, recordDB } = require('../../../db');
Copy link
Member

Choose a reason for hiding this comment

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

userDB에도 접근 안하는거 같아용~

Copy link
Contributor Author

Choose a reason for hiding this comment

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

삭제했어요!

const jwtHandlers = require('../../../lib/jwtHandlers');
const slackAPI = require('../../../middlewares/slackAPI');
const dayjs = require('dayjs');
const { filter } = require('lodash');
const _ = require('lodash');

/**
* @인증사진_모아보기
* @route GET /myroom/room/:roomId?lastid=&size=
* @error
* 1. roomId가 없음
* 2. 존재하지 않는 습관방인 경우
* 3. 접근 권한이 없는 유저인 경우
*/


module.exports = async (req, res) => {
let lastId = Number(req.query.lastid);
const size = Number(req.query.size);
const user = req.user;
const { roomId } = req.params;
let client;

// @error 1. roomId가 없음
if (!roomId) {
return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.BAD_REQUEST, responseMessage.NULL_VALUE));
}

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

const room = await roomDB.getRoomById(client, roomId);
// @error 2. 존재하지 않는 습관방인 경우
if (!room) {
res.status(statusCode.NO_CONTENT).send(util.fail(statusCode.NO_CONTENT, responseMessage.GET_ROOM_DATA_FAIL));
}

// @error 3. 접근 권한이 없는 유저인 경우
const entry = await roomDB.checkEnteredById(client, roomId, user.userId);
if (!entry) {
res.status(statusCode.UNAUTHORIZED).send(util.fail(statusCode.UNAUTHORIZED, responseMessage.NOT_MEMBER));
}

const pagedRecords = await recordDB.getPagedRecordsByEntryId(client, entry.entryId, lastId, size);

// 해당하는 record가 없을 경우
if (!pagedRecords.length) {
const data = {
roomName: room.roomName,
records: []
};
return res.status(statusCode.OK).send(util.success(statusCode.OK, responseMessage.GET_MYROOM_DETAIL_SUCCESS, data));
}

const recordIds = pagedRecords.map((o) => o.recordId);

const sparkNums = await sparkDB.countSparkByRecordIds(client, recordIds);

const records = pagedRecords.map((record) => {
const sparkCount = _.find(sparkNums, {'recordId': record.recordId});
const sparkNum = sparkCount? Number(sparkCount.sparkNum): 0;
return {
recordId: record.recordId,
leftDay: 66-record.dayjs,
certifyingImg: record.certifyingImg,
sparkNum,
status: record.status
}
});

const data = {
roomName: room.roomName,
records
};

res.status(statusCode.OK).send(util.success(statusCode.OK, responseMessage.GET_MYROOM_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();
}
};
13 changes: 6 additions & 7 deletions functions/constants/responseMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ module.exports = {
CREATE_ROOM_SUCCESS: '습관 방 생성 성공',
CREATE_ROOM_FAIL: '습관 방 생성 실패',
GET_WAITROOM_DATA_SUCCESS: '대기방 정보 확인 완료',
GET_WAITROOM_DATA_IMPOSSIBLE: '참여할 수 없는 코드예요.',
GET_WAITROOM_DATA_NULL: '존재하지 않는 코드예요.',
GET_WAITROOM_DATA_IMPOSSIBLE: '참여할 수 없는 코드에요.',
GET_WAITROOM_DATA_NULL: '존재하지 않는 코드에요.',
Comment on lines -28 to +29
Copy link
Member

Choose a reason for hiding this comment

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

이거 머지하면서 지우신게 제가 수정한 내용인데, 요거 "예요"가 맞는 문법이라구 하네용!
추가하신 내용 삭제하시구, 지우신 내용으로 대체 해주시면 될거같아요!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

수정했어요!

GET_WAITROOM_DATA_STARTED: '이미 습관 형성에 도전중인 방입니다',
GET_WAITROOM_DATA_ALREADY: '이미 참여 중인 코드에요.',
GET_WAITROOM_DATA_FAIL: '대기방 정보 확인 실패',
Expand Down Expand Up @@ -55,6 +55,10 @@ module.exports = {
// Spark
CANNOT_SEND_SPARK_SELF: '자기자신에게 스파크를 보낼 수 없습니다',
SEND_SPARK_SUCCESS: '스파크 전송 선공',

// Myroom
GET_MYROOM_SUCCESS: '보관함 리스트 불러오기 성공',
GET_MYROOM_DETAIL_SUCCESS: '인증사진 모아보기 성공',

// Notice
SERVICE_READ_SUCCESS: '서비스 알림 읽음처리 완료',
Expand All @@ -64,9 +68,4 @@ module.exports = {
NOTICE_DELETE_SUCCESS: '알림 삭제 완료',
NOTICE_ID_NOT_VALID: '유효하지 않은 알림 ID 입니다',
PUSH_SEND_SUCCESS: '푸시알림 전송 완료',

// 인증
INVALID_USER_STATUS: '유효하지 않은 status type입니다',
CERTIFICATION_ALREADY_DONE: '이미 인증을 완료하였습니다',
UPDATE_STATUS_SUCCESS: '상태 변경 완료',
};
32 changes: 32 additions & 0 deletions functions/db/record.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,41 @@ const uploadRecord = async (client, recordId, certifyingImg, timerRecord) => {
return convertSnakeToCamel.keysToCamel(rows[0]);
};

const getPagedRecordsByEntryId = async (client, entryId, lastId, size) => {
if (lastId === -1) {
const { rows } = await client.query(
`
SELECT *
FROM spark.record r
WHERE r.entry_id = $1
ORDER BY r.day DESC
LIMIT $2
`,
[entryId, size]
);
return convertSnakeToCamel.keysToCamel(rows);
}
else {
const { rows } = await client.query(
`
SELECT *
FROM spark.record r
WHERE r.entry_id = $1
AND r.record_id < $2
ORDER BY r.day DESC
LIMIT $3
`,
[entryId, lastId, size]
);
return convertSnakeToCamel.keysToCamel(rows);

}
};

module.exports = {
insertRecordById,
getRecentRecordByEntryId,
updateStatusByRecordId,
uploadRecord,
getPagedRecordsByEntryId
};
13 changes: 13 additions & 0 deletions functions/db/spark.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,22 @@ const countSparkByEntryId = async (client, entryId) => {
return convertSnakeToCamel.keysToCamel(rows);
}

const countSparkByRecordIds = async (client, recordIds) => {
const { rows } = await client.query(
`
SELECT s.record_id, COUNT(record_id) AS spark_num
FROM spark.spark s
WHERE record_id in (${recordIds.join()})
GROUP BY record_id
`,
);
return convertSnakeToCamel.keysToCamel(rows);
}

module.exports = {
countSparkByRecordId,
insertSpark,
countSparkByEntryId,
countSparkByRecordIds
};