Skip to content

Commit

Permalink
Merge branch 'develop' into feature/#35
Browse files Browse the repository at this point in the history
  • Loading branch information
youngkwon02 authored Jan 13, 2022
2 parents 647943f + b5eb9a7 commit 4caf6f6
Show file tree
Hide file tree
Showing 13 changed files with 384 additions and 14 deletions.
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;
3 changes: 3 additions & 0 deletions functions/api/routes/notice/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
const express = require('express');
const router = express.Router();
const { checkUser } = require('../../../middlewares/auth');

router.use('/active', require('./active'));
router.use('/service', require('./service'));

router.delete('/:noticeId', checkUser, require('./noticeDELETE'));

module.exports = router;
54 changes: 54 additions & 0 deletions functions/api/routes/notice/noticeDELETE.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const functions = require('firebase-functions');
const util = require('../../../lib/util');
const statusCode = require('../../../constants/statusCode');
const responseMessage = require('../../../constants/responseMessage');
const db = require('../../../db/db');
const { noticeDB } = require('../../../db');

/**
* @서비스_및_활동_알림_삭제
* @route GET /notice/:noticeId
* @error
* 1. 알림 id가 전달되지 않음
* 2. 올바르지 않은 noticeId가 전달된 경우
* 3. 알림 삭제 권한이 없는 사용자가 요청을 보낸 경우
*/

module.exports = async (req, res) => {
const { noticeId } = req.params;
const user = req.user;
const userId = user.userId;

// @error 1. 알림 id가 전달되지 않음
if (!noticeId) {
return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.BAD_REQUEST, responseMessage.NULL_VALUE));
}

let client;

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

const notice = await noticeDB.getNoticeByNoticeId(client, noticeId);

// @error 2. 올바르지 않은 noticeId가 전달된 경우
if (!notice) {
return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.BAD_REQUEST, responseMessage.NOTICE_ID_NOT_VALID));
}

// @error 3. 알림 삭제 권한이 없는 사용자가 요청을 보낸 경우
if (userId !== notice.receiverId) {
return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.BAD_REQUEST, responseMessage.PRIV_NOT_FOUND));
}

await noticeDB.deleteNoticeByNoticeId(client, noticeId);

res.status(statusCode.OK).send(util.success(statusCode.OK, responseMessage.NOTICE_DELETE_SUCCESS));
} catch (error) {
functions.logger.error(`[ERROR] [${req.method.toUpperCase()}] ${req.originalUrl}`, `[CONTENT] ${error}`);
console.log(error);
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/api/routes/room/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ const { checkUser } = require('../../../middlewares/auth');

router.get('/code/:code', checkUser, require('./roomCodeGET'));
router.post('', checkUser, require('./roomPOST'));
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'));

module.exports = router;
114 changes: 114 additions & 0 deletions functions/api/routes/room/roomDetailGET.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
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');

/**
* @습관방_상세_조회
* @route GET /room/:roomId
* @error
* 1. 존재하지 않는 습관방인 경우
* 2. 진행중인 습관방이 아닌 경우
* 3. 접근 권한이 없는 유저인 경우
*/

module.exports = async (req, res) => {
const { roomId } = req.params;
const user = req.user;

let client;

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

const room = await roomDB.getRoomById(client, roomId);

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;

// @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);

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();
}
};
56 changes: 56 additions & 0 deletions functions/api/routes/room/roomEnterPOST.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const functions = require('firebase-functions');
const util = require('../../../lib/util');
const statusCode = require('../../../constants/statusCode');
const responseMessage = require('../../../constants/responseMessage');
const db = require('../../../db/db');
const { roomDB } = require('../../../db');

/**
* @습관방_참여
* @route POST /room/:roomId/enter
* @body
* @error
* 1. roomId가 올바르지 않음 (이미 삭제된 방이거나 존재하지 않은 방)
* 2. 사용자가 이미 참여중인 방임
* 3. 습관방 참여 실패
*/

module.exports = async (req, res) => {
const { roomId } = req.params;
const user = req.user;
const userId = user.userId;

let client;

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

const room = await roomDB.getRoomById(client, roomId);

// @error 1. roomId가 올바르지 않음 (이미 삭제된 방이거나 존재하지 않은 방)
if (!room) {
return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.BAD_REQUEST, responseMessage.ROOM_ID_INVALID));
}

// @error 2. 사용자가 이미 참여중인 방임
const isEntered = await roomDB.checkEnteredById(client, roomId, userId);
if (isEntered) {
return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.BAD_REQUEST, responseMessage.ENTER_ROOM_ALREADY));
}

const enterEntry = await roomDB.enterById(client, roomId, userId);
// @error 3. 습관 방 참여 실패
if (!enterEntry) {
return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.BAD_REQUEST, responseMessage.ENTER_ROOM_FAIL));
}

res.status(statusCode.OK).send(util.success(statusCode.OK, responseMessage.ENTER_ROOM_SUCCESS));
} catch (error) {
functions.logger.error(`[ERROR] [${req.method.toUpperCase()}] ${req.originalUrl}`, `[CONTENT] ${error}`);
console.log(error);

res.status(statusCode.INTERNAL_SERVER_ERROR).send(util.fail(statusCode.INTERNAL_SERVER_ERROR, responseMessage.INTERNAL_SERVER_ERROR));
} finally {
client.release();
}
};
2 changes: 1 addition & 1 deletion functions/api/routes/room/roomPOST.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const util = require('../../../lib/util');
const statusCode = require('../../../constants/statusCode');
const responseMessage = require('../../../constants/responseMessage');
const db = require('../../../db/db');
const { userDB, roomDB } = require('../../../db');
const { roomDB } = require('../../../db');
const { nanoid } = require('nanoid');

module.exports = async (req, res) => {
Expand Down
9 changes: 9 additions & 0 deletions functions/constants/responseMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,21 @@ module.exports = {
GET_WAITROOM_DATA_ALREADY: '이미 사용자가 참가중인 방입니다',
GET_WAITROOM_DATA_FAIL: '대기방 정보 확인 실패',
GET_WAITROOM_DATA_KICKED: '습관 방 생성자에 의해 내보내진 방입니다',
ENTER_ROOM_SUCCESS: '습관 방 참여 완료',
ENTER_ROOM_FAIL: '습관 방 참여 실패',
ENTER_ROOM_ALREADY: '이미 참여중인 습관 방입니다',
ROOM_ID_INVALID: '올바르지 않은 roomId입니다',
PURPOSE_SET_SUCCESS: '목표 설정 성공',
ROOM_ID_NOT_FOUND: '유효하지 않은 roomId입니다',
GET_ROOM_DATA_FAIL: '존재하지 않는 습관방입니다',
NOT_ONGOING_ROOM: '현재 진행중인 습관방이 아닙니다',
NOT_MEMBER: '참여중인 습관방이 아닙니다',

// Notice
SERVICE_READ_SUCCESS: '서비스 알림 읽음처리 완료',
ACTIVE_READ_SUCCESS: '활동 알림 읽음처리 완료',
SERVICE_GET_SUCCESS: '서비스 알림 조회 완료',
ACTIVE_GET_SUCCESS: '활동 알림 조회 완료',
NOTICE_DELETE_SUCCESS: '알림 삭제 완료',
NOTICE_ID_NOT_VALID: '유효하지 않은 알림 ID 입니다',
};
1 change: 1 addition & 0 deletions functions/db/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module.exports = {
userDB: require('./user'),
roomDB: require('./room'),
sparkDB: require('./spark'),
noticeDB: require('./notice'),
};
Loading

0 comments on commit 4caf6f6

Please sign in to comment.