Skip to content

Commit

Permalink
Merge pull request #55 from Together42/issue/30
Browse files Browse the repository at this point in the history
Merge: Issue/30
  • Loading branch information
kth2624 authored May 8, 2022
2 parents 01bb5ce + 4cf5554 commit 1a52624
Show file tree
Hide file tree
Showing 10 changed files with 108 additions and 195 deletions.
2 changes: 1 addition & 1 deletion config/winston.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const logger = winston.createLogger({
level: 'info',
datePattern: 'YYYYMMDD',
dirname: './logs',
filename: `appName_%DATE%.log`,
filename: `together_%DATE%.log`,
maxSize: null,
maxFiles: 14
}),
Expand Down
5 changes: 5 additions & 0 deletions controller/auth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ export async function signUp(req, res) {
if(user){ //이미 존재하는 사용자라면
return res.status(400).json({message: `${intraId} already exists`});
}

const checkEmail = await userRepository.findByEmail(email);
if(checkEmail){ //이미 존재하는 이메일
return res.status(400).json({message: `${email} already exists`});
}
const hashed = await bcrypt.hash(password, config.bcrypt.saltRounds);
const userId = await userRepository.createUser({
intraId,
Expand Down
139 changes: 39 additions & 100 deletions controller/board.controller.js
Original file line number Diff line number Diff line change
@@ -1,116 +1,55 @@
import * as boardRepository from '../data/board.js';
import * as userRepository from '../data/auth.js';

export async function createEvent(req, res) {
const { title, description } = req.body;
const user = await userRepository.findById(req.userId);
console.log(user);
const createdBy = user.id;
const event = await togetherRepository.createEvent({
import * as togetherRepository from '../data/together.js';
import * as togetherController from './together.controller.js';

//게시글 생성
export async function createPost(req, res) {
const { title, contents, image, eventId, attendMembers } = req.body;
const writerId = req.userId;
const post = await boardRepository.createPost({
writerId,
title,
description,
createdBy,
contents,
image,
eventId,
attendMembers
});
res.status(201).json({event});
res.status(201).json({post});
}

export async function deleteEvent(req, res){
//게시글 삭제
export async function deletePost(req, res){
const id = req.params.id;
const deleteId = await togetherRepository.findByEventId(id);
const user = await userRepository.findById(req.userId);
const createUser = user.id;
const deleteId = await boardRepository.findByPostId(id);
console.log(deleteId);

if(!deleteId) //삭제할 친바가 없다면
return res.status(404).json({message: 'Event not found'});

//권한
if(deleteId.createdBy !== createUser)
if(!deleteId) //삭제할 글이 없다면
return res.status(404).json({message: 'Post not found'});
if(deleteId.writerId !== req.userId)//권한
return res.status(401).json({message: 'UnAuthorization User'});

await togetherRepository.deleteEvent(id);
await boardRepository.deletePost(id);
res.sendStatus(204);
}

export async function getEventList(req, res){
const EventList = await togetherRepository.getEventList();
res.status(200).json({EventList});
}

//상세조회 , 유저객체정보를 배열로 넘겨달라
export async function getEvent(req, res){
//게시글 수정
//일단 제목, 내용만 수정가능, / 사진은 추후에
export async function updatePost (req, res) {
const id = req.params.id;
const event = await togetherRepository.findByEventId(id);
if(!event) //조회할 친바가 없다면
return res.status(404).json({message: 'Event not found'});
const teamList = await getTeamList(id);

res.status(200).json({event, teamList});
}

export async function register(req, res){
const user = await userRepository.findById(req.userId);//토큰으로 받아온 아이디
const eventId = req.body.eventId;
const alreadyAttend = await togetherRepository.findByAttend(user.id, eventId)
if(alreadyAttend) //이미 참석했다면
return res.status(400).json({message: 'already attend'});
const attend = await togetherRepository.register(user.id, eventId);
res.status(201).json({attend});
}

export async function unregister(req, res){
const user = await userRepository.findById(req.userId);//토큰으로 받아온 아이디
const eventId = req.params.id;//event id
const alreadyAttend = await togetherRepository.findByAttend(user.id, eventId)
if(!alreadyAttend) //참석이 없으면
return res.status(400).json({message: 'Attend not found'});
//teamId가 있으면(즉 팀 매칭이 완료된경우)
if(alreadyAttend.teamId !== null)
return res.status(400).json({message: 'already matching'});

await togetherRepository.unregister(user.id, eventId);
res.sendStatus(204);
}

async function getTeamList(id) //중복되는 부분이여서 함수로빼냄
{
const matchingList = await togetherRepository.getMatchingList(id);
//teamId(키)로 객체에서 배열 그룹화
let teamList = matchingList.reduce(function (r, a) {
r[a.teamId] = r[a.teamId] || [];
r[a.teamId].push(a);
return r;
}, Object.create(null));
return teamList;
}

export async function getTeam(req, res){
const id = req.params.id;//event id
const teamList = await getTeamList(id);
res.status(200).json({teamList});
}

export async function matching(req, res) {
const {eventId, teamNum } = req.body;
const check = await togetherRepository.findAttendByEventId(eventId)

if(check === undefined || check[0].teamId !== null) //참석자가 없거나, 이미 매칭이 된경우
return res.status(400).json({message: 'already matching or not exists'});

if(check.length < teamNum) //유저보다 팀 개수가 많을때
return res.status(400).json({message: 'Too few attendees'});
shuffle(check);//팀 셔플완료 이제 팀개수대로 팀 나눠야함

for(let i = 0; i < check.length; i++)
{
let teamId = i % teamNum + 1;
await togetherRepository.createTeam(teamId, check[i].id);
console.log(`id=${check[i].id}, team=${teamId}`);
const {title, contents, image, eventId, attendMembers} = req.body;
//제목이 없을시 에러
if(title == '')
return res.status(400).json({message: 'title not found'});

const updateId = await boardRepository.findByPostId(id);
if(!updateId) {//해당 게시글이 없다면
return res.status(404).json({message: 'Post not found'});
}

res.status(201).json(await getTeamList(eventId));
if(updateId.writerId !== req.userId){
return res.status(401).json({message: 'UnAuthorization User'});
}
const updated = await boardRepository.updatePost({id, title, contents, image, eventId, attendMembers});
res.status(200).json({updated});
}

//팀 셔플
function shuffle(array){
array.sort(()=> Math.random() - 0.5);
}

30 changes: 23 additions & 7 deletions controller/together.controller.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as togetherRepository from '../data/together.js';
import * as userRepository from '../data/auth.js';

//이벤트 생성
export async function createEvent(req, res) {
const { title, description } = req.body;
const user = await userRepository.findById(req.userId);
Expand All @@ -14,44 +15,46 @@ export async function createEvent(req, res) {
res.status(201).json({event});
}

//이벤트 삭제
export async function deleteEvent(req, res){
const id = req.params.id;
const deleteId = await togetherRepository.findByEventId(id);
const user = await userRepository.findById(req.userId);
const createUser = user.id;

if(!deleteId) //삭제할 친바가 없다면
return res.status(404).json({message: 'Event not found'});

//권한
return res.status(404).json({message: 'Event not found1'});
//권한
console.log(deleteId);
if(deleteId.createdId !== createUser)
{
console.log(`?? ${deleteId.createdId} user=${createUser}`);
return res.status(401).json({message: 'UnAuthorization User'});

}

await togetherRepository.deleteEvent(id);
res.sendStatus(204);
}

//전체 이벤트 조회
export async function getEventList(req, res){
const EventList = await togetherRepository.getEventList();
res.status(200).json({EventList});
}

//상세조회 , 유저객체정보를 배열로 넘겨달라
//이벤트 상세조회 , 유저객체정보를 배열로 넘겨달라
export async function getEvent(req, res){
console.log("오잉?");
const id = req.params.id;
const event = await togetherRepository.findByEventId(id);
if(!event) //조회할 친바가 없다면
return res.status(404).json({message: 'Event not found'});
return res.status(404).json({message: 'Event not found2'});
const teamList = await getTeamList(id);

res.status(200).json({event, teamList});
}

//이벤트 참석
export async function register(req, res){
const user = await userRepository.findById(req.userId);//토큰으로 받아온 아이디
const eventId = req.body.eventId;
Expand All @@ -61,7 +64,7 @@ export async function register(req, res){
const attend = await togetherRepository.register(user.id, eventId);
res.status(201).json({attend});
}

//이벤트 참석해제
export async function unregister(req, res){
const user = await userRepository.findById(req.userId);//토큰으로 받아온 아이디
const eventId = req.params.id;//event id
Expand Down Expand Up @@ -119,4 +122,17 @@ export async function matching(req, res) {
//팀 셔플
function shuffle(array){
array.sort(()=> Math.random() - 0.5);
}

//게시글 작성을 위한 정보 조회 (모든 이벤트, 팀리스트)
export async function getEventInfo (req, res) {
let eventList = await togetherRepository.getEventList();
console.log("hi");
for(let i = 0; i < eventList.length; i++)
{
const team = await getTeamList(eventList[i].id);
eventList[i].teamList = team;
}
console.log(eventList);
res.status(200).json(eventList);
}
6 changes: 6 additions & 0 deletions data/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ export async function findByintraId(intraId) {
.then((result) => result[0][0]);
}

export async function findByEmail(email) {
return db
.execute('SELECT * FROM users WHERE email=?',[email])
.then((result) => result[0][0]);
}

export async function createUser(user) {
const {intraId, password, email, url} = user;
return db
Expand Down
85 changes: 14 additions & 71 deletions data/board.js
Original file line number Diff line number Diff line change
@@ -1,84 +1,27 @@
import { db } from '../db/database.js';

export async function getEventList(){
export async function findByPostId(id) {
return db
.execute('SELECT ev.id, ev.title, ev.description at.teamId FROM event_info as ev JOIN attendance_info as at ON ev.id=at.id ')
.then((result)=>console.log(result[0]));
}

export async function findByEventId(id) {
return db
.execute('SELECT * FROM event_info WHERE id=?',[id])
.execute('SELECT * FROM board WHERE id=?',[id])
.then((result) => result[0][0]);
}

export async function deleteEvent(id) {
return db.execute('DELETE FROM event_info WHERE id=?',[id]);
export async function deletePost(id) {
return db.execute('DELETE FROM board WHERE id=?',[id]);
}

export async function createEvent(event) {
const {title, description, createdBy} = event;
export async function createPost(post) {
const {writerId, title, contents, image, eventId, attendMembers} = post;
return db
.execute('INSERT INTO event_info (title, description, createdBy) VALUES (?,?,?)',
[title, description, createdBy]
.execute('INSERT INTO board (writerId, title, contents, image, eventId, attendMembers) VALUES (?,?,?,?,?,?)',
[writerId, title, contents, image, eventId, attendMembers]
)
.then((result) => result[0].insertId);
}

export async function register(user, eventId) {
return db
.execute('INSERT INTO attendance_info (userId, eventId) VALUES (?,?)',
[user, eventId]
)
.then((result)=> result[0].insertId);
}

export async function unregister(user, eventId) {
return db
.execute('DELETE FROM attendance_info WHERE userId=? && eventId=?',
[user, eventId]
)
}

export async function findByAttend(user, eventId) {
return db
.execute('SELECT * FROM attendance_info WHERE userId=? && eventId=?',
[user, eventId]
)
.then((result) => result[0][0]);
}

export async function findAttendByEventId(eventId) {
return db
.execute('SELECT * FROM attendance_info WHERE eventId=?',
[eventId]
)
.then((result) => result[0]);
}

export async function getMatchingList(id)
{
return db
.execute('SELECT us.loginId, us.url, at.teamId from attendance_info as at JOIN users as us ON at.userId=us.id WHERE at.eventId=? ORDER BY at.teamId',
[id]
)
.then((result) => result[0]);
}


export async function getByAttendId(id)
{
return db
.execute('SELECT * FROM attendance_info WHERE id=?',
[id]
)
.then((result)=> result[0][0]);
}

export async function createTeam(teamId, id)
{
return db
.execute('UPDATE attendance_info SET teamId=? WHERE id=?',
[teamId, id])
.then(()=> getByAttendId(id));
}
export async function updatePost(post) {
const {id, title, contents, image, eventId, attendMembers} = post;
return db.execute('UPDATE board SET title=? ,contents=? ,image=? ,eventId=? ,attendMembers=? WHERE id=?',
[title, contents, image, eventId, attendMembers, id])
.then(()=> findByPostId(id));
}
1 change: 1 addition & 0 deletions db/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const pool = mysql.createPool({
user: config.db.user,
database: config.db.database,
password: config.db.password,
dateStrings: 'date',
})

export const db = pool.promise();
3 changes: 0 additions & 3 deletions routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,6 @@ const validateCredential = [
//회원가입 유효성 검사
const validateSignup= [
...validateCredential,
//body('nickName')
// .notEmpty()
// .withMessage('nickName is missing'),
body('email')
.isEmail()
.normalizeEmail()
Expand Down
Loading

0 comments on commit 1a52624

Please sign in to comment.