-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
906 lines (741 loc) · 30.3 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
require('dotenv').config();
const express = require('express');
const mysql = require('mysql2/promise');
const bcrypt = require('bcrypt');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const { body, validationResult } = require('express-validator');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const cors_origin = process.env.CORS_ORIGIN || 'http://localhost:3000';
const io = socketIo(server, {
cors: {
origin: cors_origin,
credentials: true,
},
});
app.use(express.json());
app.use(cors({
origin: cors_origin,
credentials: true,
}));
// 데이터베이스 설정을 환경 변수로 관리
const db = mysql.createPool({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
});
// 데이터베이스 연결 확인
(async () => {
try {
await db.getConnection();
console.log('Database connected successfully');
} catch (error) {
console.error('Database connection failed:', error);
}
})();
// JWT 비밀키를 환경 변수로 설정
const JWT_SECRET = process.env.JWT_SECRET;
// JWT 인증 미들웨어
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.sendStatus(401); // Unauthorized
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
return res.sendStatus(403); // Forbidden
}
req.user = user;
next();
});
};
// 소켓 연결 처리
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('joinRoom', ({ chatRoomId }) => {
socket.join(chatRoomId);
console.log('User joined room: ${chatRoomId}');
});
socket.on('chatMessage', async ({ chatRoomId, senderId, message }) => {
try {
// 대화 내용을 messages 테이블에 저장
const sql = 'INSERT INTO messages (chat_id, sender_id, message, created_at) VALUES (?, ?, ?, NOW())';
await db.query(sql, [chatRoomId, senderId, message]);
// 메시지를 방에 있는 모든 사용자에게 전송
io.to(chatRoomId).emit('message', {
senderId,
message,
timestamp: new Date().toISOString(),
});
} catch (error) {
console.error('Error saving message:', error);
}
});
socket.on('disconnect', () => {
console.log('A user disconnected');
});
});
// Register
// 사용자 등록 -> Register.jsx
app.post('/api/register', [
body('name').isString().withMessage('Name must be a string'),
body('age').isInt({ min: 1 }).withMessage('Age must be a positive integer'),
body('studentId').isString().withMessage('Student ID must be a string'),
body('department').isString().withMessage('Department must be a string'),
body('username')
.matches(/^[A-Za-z0-9@_\-~]+$/).withMessage('Username can only contain letters, numbers, and special characters (@, _, -, ~)')
.notEmpty().withMessage('Username is required'),
body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long')
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, age, studentId, department, username, password } = req.body;
try {
const hashedPassword = await bcrypt.hash(password, 10);
const sql = 'INSERT INTO users (name, age, student_id, department, username, password) VALUES (?, ?, ?, ?, ?, ?)';
await db.query(sql, [name, age, studentId, department, username, hashedPassword]);
res.status(201).json({ message: 'User registered successfully' });
} catch (error) {
console.error('Registration error:', error);
res.status(500).json({ error: 'Registration failed', details: error.message });
}
});
// LoginForm
// 사용자 로그인 -> LoginForm.jsx
app.post('/api/login', async (req, res) => {
const { username, password } = req.body;
const sql = 'SELECT * FROM users WHERE username = ?';
try {
const [results] = await db.query(sql, [username]);
if (results.length > 0) {
const user = results[0];
const match = await bcrypt.compare(password, user.password);
if (match) {
const token = jwt.sign({ id: user.id, username: user.username }, JWT_SECRET, { expiresIn: '24h' });
return res.json({ message: 'Login successful', token });
}
}
res.status(401).json({ error: 'Invalid credentials' });
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ error: 'Login failed', details: error.message });
}
});
// Home
// 홈 데이터 가져오기 -> Home.jsx
app.get('/api/home', authenticateToken, async (req, res) => {
const userId = req.user.id;
try {
const currentMonth = new Date().getMonth() + 1;
const [calendarResults] = await db.query(
'SELECT * FROM calendar WHERE user_id = ? AND MONTH(start_date) = ?',
[userId, currentMonth]
);
const [stickyResults] = await db.query('SELECT * FROM sticky WHERE user_id = ?', [userId]);
res.json({
calendar: calendarResults,
sticky: stickyResults,
});
} catch (error) {
console.error('Error fetching data:', error);
res.status(500).json({ error: 'Error fetching data', details: error.message });
}
});
// Calendar
// 이벤트 확인 -> Calendar.jsx
app.get('/api/events', authenticateToken, async (req, res) => {
const userId = req.user.id;
const query = 'SELECT * FROM calendar WHERE user_id = ?';
try {
const [results] = await db.query(query, [userId]);
res.status(201).json({events: results, userId: userId});
} catch (error) {
console.error('Error fetching events:', error);
res.status(500).json({ error: 'Error fetching events', details: error.message});
};
});
// 이벤트 저장 -> Calendar.jsx
app.post('/api/events', authenticateToken, async (req, res) => {
const user_id = req.user.id;
const { title, description, start_date, end_date, all_day, color } = req.body;
const query = `
INSERT INTO calendar (user_id, title, description, start_date, end_date, all_day, color, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW() )`;
const [calendarEvents] = await db.query(query, [user_id, title, description, start_date, end_date, all_day, color]);
if(!calendarEvents){
console.log("undefined");
}
return res.json({ saveEventId: calendarEvents });
});
// 이벤트 수정 -> Calendar.jsx
app.put('/api/events/:id', authenticateToken, async (req, res) => {
const { id } = req.params; // id 추출 방식 수정
const { title, description, start_date, end_date, all_day, color } = req.body;
// 필수 필드 확인
if (!title || !start_date || !end_date) {
return res.status(400).send('Title, start_date, and end_date are required');
}
try {
const sql = 'UPDATE calendar SET title = ?, description = ?, start_date = ?, end_date = ?, all_day = ?, color = ? WHERE id = ?'; // 쉼표 오류 수정
const [results] = await db.query(sql, [title, description, start_date, end_date, all_day, color, id]);
res.status(200).json({ updateEvent: results }); // 상태 코드 수정
} catch (error) {
console.error('Database error:', error);
return res.status(500).send('Error updating event');
}
});
// 이벤트 삭제 -> Calendar.jsx
app.delete('/api/events/:id', authenticateToken, async (req, res) => {
const id = req.params.id; // URL에서 이벤트 ID 가져오기
const userId = req.user.id; // 로그인한 사용자의 ID
try {
const sql = 'DELETE FROM calendar WHERE id = ? AND user_id = ?';
const [result] = await db.query(sql, [id, userId]);
if (result.affectedRows === 0) {
return res.status(404).json({ error: 'Sticky note not found or not authorized to delete' });
}
res.json({ message: 'Sticky note deleted successfully' });
} catch (error) {
res.status(500).send('Error deleting event');
}
});
// Sticky
// Sticky 노트 데이터 가져오기
app.get('/api/stickys', authenticateToken, async (req, res) => {
const userId = req.user.id;
try {
const [stickyResults] = await db.query('SELECT * FROM sticky WHERE user_id = ?', [userId]);
res.json({ sticky: stickyResults });
} catch (error) {
console.error('Error fetching sticky notes:', error);
res.status(500).json({ error: 'Error fetching sticky notes', details: error.message });
}
});
// Sticky 노트 생성
app.post('/api/stickys', authenticateToken, async (req, res) => {
const userId = req.user.id;
const { content, position_x, position_y, width, height } = req.body;
try {
const sql = `INSERT INTO sticky (user_id, content, position_x, position_y, width, height, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())`;
const [stickyResults] = await db.query(sql, [userId, content, position_x, position_y, width, height]);
console.log(stickyResults);
res.status(201).json({ sticky: stickyResults });
} catch (error) {
console.error('Error creating sticky note:', error);
res.status(500).json({ error: 'Failed to create sticky note', details: error.message });
}
});
// Sticky 노트 수정
app.put('/api/stickys/:id', authenticateToken, async (req, res) => {
const userId = req.user.id;
const id = req.params.id;
const { content, position_x, position_y, width, height } = req.body;
try {
const sql = `UPDATE sticky
SET content = ?, position_x = ?, position_y = ?, width = ?, height = ?, updated_at = NOW()
WHERE id = ? AND user_id = ?`;
const [result] = await db.query(sql, [content, position_x, position_y, width, height, id, userId]);
if (result.affectedRows === 0) {
return res.status(404).json({ error: 'Sticky note not found or not authorized to update' });
}
res.json({ message: 'Sticky note updated successfully' });
} catch (error) {
console.error('Error updating sticky note:', error);
res.status(500).json({ error: 'Failed to update sticky note', details: error.message });
}
});
// Sticky 노트 삭제
app.delete('/api/stickys/:id', authenticateToken, async (req, res) => {
const userId = req.user.id;
const id = req.params.id;
try {
const sql = `DELETE FROM sticky WHERE id = ? AND user_id = ?`;
const [result] = await db.query(sql, [id, userId]);
if (result.affectedRows === 0) {
return res.status(404).json({ error: 'Sticky note not found or not authorized to delete' });
}
res.json({ message: 'Sticky note deleted successfully' });
} catch (error) {
console.error('Error deleting sticky note:', error);
res.status(500).json({ error: 'Failed to delete sticky note', details: error.message });
}
});
// To-Do 항목 가져오기 -> To Do.jsx
app.get('/api/todos', authenticateToken, async (req, res) => {
const userId = req.user.id;
try {
const sql = 'SELECT id, content, completed FROM todos WHERE user_id = ?'; // id도 가져오도록 수정
const [rows] = await db.query(sql, [userId]);
res.json({ todos: rows });
} catch (error) {
console.error('Error fetching to-do items:', error);
res.status(500).json({ error: 'Failed to fetch to-do items' });
}
});
// 새로운 To-Do 항목 추가하기 -> To Do.jsx
app.post('/api/todos', authenticateToken, async (req, res) => {
const userId = req.user.id;
const { content, completed } = req.body;
try {
const sql = 'INSERT INTO todos (user_id, content, created_at, updated_at, completed) VALUES (?, ?, NOW(), NOW(), ?)';
const [result] = await db.query(sql, [userId, content, completed]);
const newTodo = {
id: result.insertId,
userId: userId,
content: content,
completed, completed,
};
res.status(201).json({ newTodo: newTodo }); // 새로 추가된 항목 반환
} catch (error) {
console.error('Error creating to-do item:', error);
res.status(500).json({ error: 'Failed to create to-do item' });
}
});
// To-Do Completed 패칭
app.patch('/api/todos/:id', authenticateToken, async (req,res) => {
const userId = req.user.id;
const { id } = req.params;
const { completed } = req .body;
try {
const sql = 'UPDATE todos SET completed = ? WHERE id = ? AND user_id = ? ';
await db.query(sql, [completed, id, userId]);
res.status(200).json({ message: 'Todo item chekced update successfully' });
} catch (error) {
console.error('Error patching to-do items', error);
res.status(500).json({ error: 'Failed to patching to-do item' });
}
});
// 특정 To-Do 항목 삭제하기 -> To Do.jsx
app.delete('/api/todos/:id', authenticateToken, async (req, res) => {
const { id } = req.params; // URL에서 전달된 id 가져오기'
db.query('DELETE FROM todos WHERE id = ?', [id], (error, results) => {
if (error) {
console.error('Error deleting todo:', error);
return res.status(500).json({ error: error.message });
}
res.status(200).json({ message: 'Todo item deleted successfully' }); // 성공 시 응답
});
});
// 정보 가져오기 -> Friends.jsx
app.get('/api/userInfo', authenticateToken, async (req, res) => {
const userId = req.user.id;
try {
// student_id 필드도 함께 선택
const [userInfoResults] = await db.query(
'SELECT id, name, student_id FROM users WHERE id = ?',
[userId]
);
if (!userInfoResults.length) {
return res.status(404).json({ error: 'User not found' });
}
// student_id 포함해서 응답 반환
res.json({
id: userInfoResults[0].id,
name: userInfoResults[0].name,
student_id: userInfoResults[0].student_id
});
} catch (error) {
console.error('Error fetching user info:', error);
res.status(500).json({ error: 'Error fetching user info', details: error.message });
}
});
// 친구 목록 가져오기 -> Friends.jsx
app.get('/api/friendsList', authenticateToken, async (req, res) => {
const userId = req.user.id;
try {
// 사용자가 속한 모든 group_id 조회
const [groupResults] = await db.query('SELECT group_id FROM group_members WHERE user_id = ?', [userId]);
if (groupResults.length > 0) {
// 모든 그룹의 ID를 추출
const groupIds = groupResults.map(group => group.group_id);
// 각 그룹의 멤버를 조회하기 위한 쿼리 (본인 제외)
const placeholders = groupIds.map(() => '?').join(', ');
const memberResults = await db.query(
`SELECT user_id FROM group_members WHERE group_id IN (${placeholders}) AND user_id != ?`,
[...groupIds, userId] // 마지막에 userId를 추가하여 본인 제외
);
const memberIds = memberResults[0].map(member => member.user_id);
if (memberIds.length > 0) {
// 멤버 정보 조회를 위한 쿼리
const memberInfoPlaceholders = memberIds.map(() => '?').join(', ');
const memberInfoSql = `SELECT * FROM users WHERE id IN (${memberInfoPlaceholders})`;
const [memberInfoResults] = await db.query(memberInfoSql, memberIds);
return res.status(200).json({ friends: memberInfoResults });
}
}
res.status(200).json({ friends: [] });
} catch (error) {
console.error('Error fetching friends:', error);
res.status(500).json({ error: 'Error fetching friends', details: error.message });
}
});
app.get('/api/chatHistory/:receiverId', authenticateToken, async (req, res) => {
const senderId = req.user.id; // 접속한 유저의 ID
const receiverId = req.params.receiverId;
try {
const sql = `
SELECT * FROM messages
WHERE
(sender_id = ? AND receiver_id = ?)
OR (sender_id = ? AND receiver_id = ?)
ORDER BY created_at ASC
`;
const [messages] = await db.query(sql, [senderId, receiverId, receiverId, senderId]);
res.status(200).json({ messages });
} catch (error) {
console.error('Error fetching chat history:', error);
res.status(500).json({ error: 'Error fetching chat history', details: error.message });
}
});
// 메시지 저장 API -> Friends.jsx
app.post('/api/saveMessage', authenticateToken, async (req, res) => {
const { sender_id, receiver_id, message } = req.body;
// SQL 쿼리 작성
const sql = 'INSERT INTO messages (sender_id, receiver_id, message, created_at) VALUES (?, ?, ?, NOW())';
try {
const [result] = await db.query(sql, [sender_id, receiver_id, message]); // 값을 SQL 쿼리에 전달
// 성공적으로 메시지가 저장된 경우
res.status(201).json({ message: '메시지가 저장되었습니다.' });
} catch (error) {
console.error('메시지 저장 실패:', error);
res.status(500).json({ error: '메시지 저장 실패', details: error.message });
}
});
// 새로운 채팅 방 생성 -> Friends.jsx
app.post('/api/chatRoom', authenticateToken, async (req, res) => {
const { userIds } = req.body;
const userId = req.user.id;
const friendId = userIds[0];
try {
// 기존에 대화가 있는지 확인
const checkSql = `
SELECT id FROM chats
WHERE (user_id = ? AND friend_id = ?)
OR (user_id = ? AND friend_id = ?)
`;
const [existingChat] = await db.query(checkSql, [userId, friendId, friendId, userId]);
if (existingChat.length > 0) {
return res.status(200).json({ chatRoomId: existingChat[0].id });
}
// 새로운 채팅 방 생성
const sql = 'INSERT INTO chats (user_id, friend_id, created_at) VALUES (?, ?, NOW())';
const [result] = await db.query(sql, [userId, friendId]);
res.status(201).json({ chatRoomId: result.insertId });
} catch (error) {
console.error('Error creating chat room:', error);
res.status(500).json({ error: 'Error creating chat room', details: error.message });
}
});
// 채팅 방 조회 API -> Friends.jsx
app.get('/api/chatRooms/:freindId', authenticateToken, async (req, res) => {
const userId = req.user.id;
const receiverId = req.params.freindId;
try {
// 사용자가 참여하고 있는 모든 채팅 방 조회
const sql = `
SELECT c.id AS chatRoomId, c.created_at AS createdAt,
CASE
WHEN c.user_id = ? THEN c.friend_id
ELSE c.user_id
END AS otherUserId
FROM chats c
WHERE c.user_id = ? OR c.friend_id = ?
ORDER BY c.created_at DESC
`;
const [chatRooms] = await db.query(sql, [userId, userId, receiverId]);
res.json({ chatRooms });
} catch (error) {
console.error('Error fetching chat rooms:', error);
res.status(500).json({ error: 'Error fetching chat rooms', details: error.message });
}
});
// 그룹 조회 -> Group.jsx
app.get('/api/groups', authenticateToken, async (req, res) => {
const userId = req.user.id;
// 그룹 멤버 테이블과 그룹 테이블을 조인하여 사용자가 속한 그룹 정보 조회
const sql = `
SELECT g.id, g.name, g.code
FROM groups g
JOIN group_members gm ON g.id = gm.group_id
WHERE gm.user_id = ?
`;
try {
const [rows] = await db.query(sql, [userId]);
res.json(rows); // 그룹 정보 반환
} catch (error) {
console.error('그룹 조회 실패:', error);
res.status(500).json({ error: 'Failed to fetch groups' });
}
});
// 그룹 생성 API -> Group.jsx
app.post('/api/createGroup', authenticateToken, async (req, res) => {
const userId = req.user.id;
const { code, name } = req.body; // 클라이언트로부터 그룹 코드와 이름을 받음
const sql = `INSERT INTO groups (code, name, created_at, updated_at, creator_id) VALUES (?, ?, NOW(), NOW(), ?)`;
const sql2 = `INSERT INTO group_members (group_id, user_id, joined_at) VALUES (?, ?, NOW())`;
try {
const [result] = await db.query(sql, [code, name, userId]);
await db.query(sql2, [result.insertId, userId]);
res.status(201).json({ success: true, groupId: result.insertId });
} catch (error) {
console.error('Error creating group:', error);
res.status(500).json({ error: 'Failed to create group' });
}
});
// 그룹 코드 중복 확인 API -> Group.jsx
app.get('/api/checkGroupCode/:code', async (req, res) => {
const groupCode = req.params.code;
const sql = `SELECT COUNT(*) AS count FROM groups WHERE code = ?`;
try {
const [rows] = await db.query(sql, [groupCode]);
res.json({ exists: rows[0].count > 0 }); // 존재 여부를 반환
} catch (error) {
console.error('Error checking group code:', error);
res.status(500).json({ error: 'Failed to check group code' });
}
});
// 그룹 가입 API -> Group.jsx
app.post('/api/joinGroup', authenticateToken, async (req, res) => {
const userId = req.user.id; // 현재 로그인한 사용자 ID
const { groupId: joinGroupCode } = req.body; // 클라이언트로부터 그룹 코드를 받음
// 그룹 코드에 해당하는 그룹 정보 조회
const sql = `SELECT id FROM groups WHERE code = ?`;
const sqlInsertMember = `INSERT INTO group_members (group_id, user_id, joined_at) VALUES (?, ?, NOW())`;
try {
const [groupRows] = await db.query(sql, [joinGroupCode]);
if (groupRows.length === 0) {
return res.status(404).json({ error: '그룹을 찾을 수 없습니다.' }); // 그룹이 존재하지 않음
}
const foundGroupId = groupRows[0].id; // 그룹 ID를 찾기 위해 foundGroupId라는 새 변수 사용
// 그룹 멤버로 추가
await db.query(sqlInsertMember, [foundGroupId, userId]);
res.status(201).json({ success: true, groupId: foundGroupId });
} catch (error) {
console.error('Error joining group:', error);
res.status(500).json({ error: '그룹 가입에 실패했습니다.' });
}
});
// 그룹 탈퇴 API -> Group.jsx
app.delete('/api/groups', authenticateToken, async (req, res) => {
const userId = req.user.id;
const { groupId } = req.body; // 클라이언트로부터 그룹 코드를 받음
// 그룹 코드에 해당하는 그룹 정보 조회
const sql = `SELECT id FROM groups WHERE code = ?`;
const sqlDeleteMember = `DELETE FROM group_members WHERE group_id = ? AND user_id = ?`;
try {
const [groupRows] = await db.query(sql, [groupId]);
if (groupRows.length === 0) {
return res.status(404).json({ error: '그룹을 찾을 수 없습니다.' }); // 그룹이 존재하지 않음
}
const groupIdFromDb = groupRows[0].id; // 변수 이름 변경
// 그룹 멤버 삭제
const [deleteResult] = await db.query(sqlDeleteMember, [groupIdFromDb, userId]);
if (deleteResult.affectedRows === 0) {
return res.status(404).json({ error: '그룹에서 탈퇴할 수 없습니다. 사용자 정보를 확인해주세요.' });
}
res.status(200).json({ success: true });
} catch (error) {
console.error('Error dropping group:', error);
res.status(500).json({ error: '그룹 탈퇴에 실패했습니다.' });
}
});
// Group To-Do
// Group To-Do 항목 가져오기
app.get('/api/groupTodos', authenticateToken, async (req, res) => {
const userId = req.user.id;
const groupId = req.query.groupId;
try {
const sql = 'SELECT id, group_id, user_id, content, completed FROM group_todos WHERE group_id =?';
const [results] = await db.query(sql, [groupId]);
res.status(201).json({ gTodo: results });
} catch (error){
console.error('Error fetching Group to-do items:', error);
res.status(500).json({ error: 'Failed to fetch Group to-do itmes' });
}
});
// Group To-Do 항목 추가하기
app.post('/api/groupTodos', authenticateToken, async (req, res) => {
const userId = req.user.id;
const { groupId, content, completed } = req.body;
try {
const sql = 'INSERT INTO group_todos (group_id, user_id, content, completed, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())';
const [result] = await db.query(sql, [groupId, userId, content, completed]);
const newTodo = {
id: result.insertId,
groupId: groupId,
userId: userId,
content: content,
completed: completed,
};
res.status(201).json({ newTodo: newTodo });
} catch (error) {
console.error('Error creating Group to-do items', error);
res.status(500).json({ error: 'Failed to create Group to-do item' });
}
});
// Group To-Do 항목 삭제하기
app.delete('/api/groupTodos/:id', authenticateToken, async (req, res) => {
const { id } = req.params;
db.query('DELETE FROM group_todos WHERE id = ?', [id], (error, result) => {
if(error) {
console.error('Error deleting Group todo:', error);
return res.status(500).json({ error: error.message });
}
res.status(200).json({ message: 'Group Todo item deleted successfully' });
});
});
// Group To-Do 체크 표시 패치하기
app.patch('/api/groupTodos/:id', authenticateToken, async (req, res) => {
const userId = req.user.id;
const { id } = req.params;
const { completed } = req.body;
try {
const sql = 'UPDATE group_todos SET completed = ? WHERE id = ?';
await db.query(sql, [completed, id]);
res.status(200).json({ message: 'Group Todo item chekced update successfully' });
} catch (error) {
console.error('Error patching Group to-do items', error);
res.status(500).json({ error: 'Failed to patching Group to-do item' });
}
});
// Notice
// Notice 항목 가져오기
app.get('/api/notice', authenticateToken, async (req, res) => {
const userId = req.user.id;
const groupId = req.query.groupId;
try {
const sql = 'SELECT id, title, content, author FROM notice WHERE group_id = ?';
const [results] = await db.query(sql, [groupId]);
res.status(201).json({ notices: results });
} catch (error) {
res.status(500).json({ error: 'Failed to fetch Notice items' });
}
});
//테스트코드
// Notice 항목 추가하기
app.post('/api/notice', authenticateToken, async (req,res) => {
const userId = req.user.id;
const { groupId, title, content } = req.body;
try {
const searchUser = 'SELECT name FROM users WHERE id = ?'
const [author] = await db.query(searchUser, [userId]);
const sql = 'INSERT INTO notice (user_id, group_id, title, content, author, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())';
const [results] = await db.query(sql, [userId, groupId, title, content, author[0].name]);
const newNotice = {
id: results.insertId,
groupId: groupId,
userId: userId,
title: title,
content: content,
author: author[0].name,
}
res.status(200).json({ newNotice: newNotice });
} catch (error) {
res.status(500).json({ error: 'Failed to creating Notice items' });
}
});
// Notice 항목 삭제하기
app.delete('/api/notice/:noticeId', authenticateToken, async (req, res) => {
const { noticeId } = req.params;
try {
const sql = 'DELETE FROM notice WHERE id = ?';
await db.query(sql, [noticeId]);
res.status(200).json({ message: 'Notice item deleted successfully' });
} catch (error) {
res.status(500).json({ error : 'Failed to deleting Notice items' });
}
});
// Notice 항목 패치하기
app.patch('/api/notice/:noticeId', authenticateToken, async (req, res) => {
const { id } = req.params;
const { title, content, groupId } = req.body;
try {
const sql = 'UPDATE notice SET title = ?, content = ? WHERE id = ? AND group_id = ?';
await db.query(sql, [title, content, id, groupId]);
res.status(200).json({ message: 'Notice item updated successfully'});
} catch (error) {
res.status(500).json({ error : 'Failed to patching Notice items' });
}
});
// Quotes 가져오기
app.get('/api/quotes', authenticateToken, async (req, res) => {
const randomNumber = req.query.randomNumber;
try {
const sql = 'SELECT content FROM quotes WHERE id = ?';
const [results] = await db.query(sql, [randomNumber]); // 결과를 results로 변경
if (results.length > 0) {
// 결과가 존재하는 경우에만 content 반환
res.status(200).json({ content: results[0].content });
} else {
// 결과가 없는 경우 처리
res.status(404).json({ message: 'Quote not found' });
}
} catch (error) {
console.error(error); // 에러 로깅
res.status(500).json({ message: 'Error fetching quotes' });
}
});
// Calendar Icon 가져오기
app.get('/api/calendarIcon', authenticateToken, async (req, res) => {
const userId = req.user.id;
try {
const sql = 'SELECT * FROM calendar_icon WHERE id = ?';
const [results] = await db.query(sql, [userId]);
res.status(200).json({ calendar_icon: results });
} catch (error) {
res.status(500).json({ message: 'Error fetching calendar_icon' });
}
});
// Calendar Icon 추가
app.post('/api/calendarIcon', authenticateToken, async (req, res) => {
const userId = req.user.id;
const { iconNumber, iconDate } = req.body;
try {
const sql = 'INSERT INTO calendar_icon (user_id, icon_number, icon_date) VALUES(?, ?, ?)';
const [results] = await db.query(sql, [userId, iconNumber, iconDate]);
if(!results)
res.status(500).json({ error: 'Failed insert Calendar Icon'});
res.status(200).json({ message: 'Success Insert Calendar Icon'});
} catch(error) {
res.status(500).json({ error: 'Error Failed insert Calendar Icon'});
}
});
// Calendar Icon 변경
app.patch('/api/calendarIcon/:iconId', authenticateToken, async (req, res) => {
const userId = req.user.id;
const { iconId } = req.params;
const { iconNumber } = req.body;
try {
const sql = 'UPDATE calendar_icon SET icon_number = ? WHERE id = ? AND user_id = ?';
await db.query(sql, [iconNumber, iconId, userId]);
res.status(200).json({ message: 'Success patch calednar icon'});
} catch (error) {
res.status(500).json({ message: 'Failed patch calendar icon'});
}
});
// Calendar Icon 삭제
app.delete('/api/calendarIcon/:iconId', authenticateToken, async (req, res) => {
const userId = req.user.id;
const { iconId } = req.params;
try {
const sql = 'DELETE FROM calendar_icon WHERE id = ? AND user_id = ?';
await db.query(sql, [iconId, userId]);
res.status(200).json({ message: 'Delete calendar_icon' });
} catch (error) {
res.status(500).json({ message: 'Failed Delete calendar_icon'});
}
});
// 서버 포트 설정
const PORT = process.env.PORT || 5000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});