-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
1503 lines (1327 loc) · 46.2 KB
/
main.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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import bodyParser from 'body-parser';
import express from 'express';
import cors from 'cors';
import con from './mysql.js';
import multer from 'multer';
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import crypto from 'crypto';
import dotenv from 'dotenv';
dotenv.config();
import { Collection } from './db.js';
import { passport } from './auth.js';
import jwt from 'jsonwebtoken';
import { verifyToken } from './jwt.js';
const randomImgName = (bytes=32)=> crypto.randomBytes(bytes).toString('hex');
const bucketName = process.env.BUCKET_NAME;
const region = process.env.S3_REGION;
const accessKey = process.env.S3_KEYID;
const secretAccessKey = process.env.S3_PRIVATEKEY;
// console.log('Region:', region);
// console.log('Access Key:', accessKey);
// console.log('Secret Access Key:', secretAccessKey);
const s3 = new S3Client({
credentials:{
accessKeyId: accessKey,
secretAccessKey: secretAccessKey
},
region: region
});
const app = express();
const port = 3000;
const storage = multer.memoryStorage();
const upload = multer({ storage: storage});
//app.use(bodyParser.json());
const corsOptions = {
origin: "http://localhost:3000",
credentials: true,
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use((req, res, next) => {
// console.log('Request Body:', req.body);
// next();
// });
const getRandomInt = (max) => {
return Math.floor(Math.random() * max);
}
app.get('/', async(req, res)=>{
let randomNumber = getRandomInt(3);
res.status(200).send(`randomNumber: ${randomNumber}`);
})
//회원
app.post('/login', (req, res, next) => {
passport.authenticate('signin', (err, user, info) => {
if (!user) {
return res.status(400).json({ message: info.message });
}
const userProfile = { userId: user.userId,
nickname: user.nickname, avatar: user.avatar, biography: user.biography}
const token = jwt.sign(
userProfile,
process.env.JWT_SECRET_KEY
);
res.json({ userProfile, token });
})(req, res, next);
});
app.post('/register', async (req, res, next) => {
try {
console.log('Request Body:', req.body);
const nickname = req.body.nickname;
// 아까 local로 등록한 인증과정 실행
passport.authenticate('signup', (passportError, user, info) => {
// 인증이 실패했거나 유저 데이터가 없다면 에러 발생
// if(emailExist){
// res.status(400).json({
// status: 400,
// message: "이미 가입한 이메일입니다."})
// return;
// }
// if(nicknameExist){
// res.status(400).json({
// status: 400,
// message: "닉네임이 중복됩니다."
// })
// return;
// }
if (passportError || !user) {
console.log('User:', user);
res.status(400).json(info);
return;
}
// user 데이터를 통해 로그인 진행
req.login(user, { session: false }, (loginError) => {
if (loginError) {
res.send(loginError);
return;
}
// 클라이언트에게 JWT 생성 후 반환
const payload = {userId: user.userId};
const token = jwt.sign(
payload,
process.env.JWT_SECRET_KEY
);
res.json({ token });
});
})(req, res);
} catch (error) {
console.error(error);
next(error);
}
});
app.get('/test', verifyToken, (req, res) => {
res.json(req.decoded);
});
app.post('/auth', passport.authenticate('jwt', {session: false}),
async(req, res, next)=>{
try{
res.json({result:true});
}catch(error){
console.error(error);
next(error);
}
});
//mainpage
//즐겨찾는 아티스트
app.get('/mainpage/favArtist', verifyToken, async (req, res) => {
const userId = req.decoded.userId; // 요청된 userId
const sql = `SELECT artists.photo, artists.artistId, artists.groupName
FROM Favorites
INNER JOIN artists ON Favorites.artistId = artists.artistId
WHERE Favorites.userId = ?;`;
con.query(sql, [userId], (err, result, fields)=>{
if(err) throw err;
const r = {
favArtistList: result // 여기에서 result는 변수명입니다. 원하는 결과 데이터로 대체되어야 합니다.
};
res.status(200).send(r);
})
});
//hot10
// app.get('/mainpage/:userId/hot10', async (req, res) => {
// const sql = `SELECT l.postId, COUNT(*) AS thisisnothing,
// pl.polaroid,
// pc.enterComp, pc.groupName, pc.memberName, pc.albumName,
// p.userId, u.nickname
// FROM Likes l
// INNER JOIN Posts p ON p.postId = l.postId
// INNER JOIN Polaroids pl ON pl.polaroidId = p.polaroidId
// INNER JOIN photoCards pc ON pl.photocardId = pc.photocardId
// INNER JOIN users u ON l.userId = u.userId
// GROUP BY l.postId
// ORDER BY thisisnothing DESC
// LIMIT 10;`;
// con.query(sql, (err, result, fields)=>{
// if(err) throw err;
// const r = {
// hot10List: result
// }
// res.status(200).send(r);
// })
// });
// //hot10 좋아요
// app.get('/mainpage/:userId/hot10/:postId/like', async(req, res)=>{
// const postId = req.params.postId;
// const sql = `SELECT postId, COUNT(*) AS likeQuant
// FROM Likes
// WHERE postId = ?
// GROUP BY postId;`;
// con.query(sql, [postId], (err, result, fields)=>{
// if(err) throw err;
// const r = {
// hot10LikeList : result
// }
// res.status(200).send(r);
// })
// })
//hot 10 좋아요 합친 버전
app.get('/mainpage/hot10', verifyToken, async(req, res)=>{
const sql = `SELECT l.postId, COUNT(*) AS likeQuant,
pl.polaroid,
pc.enterComp, pc.groupName, pc.memberName, pc.albumName,
p.userId, u.nickname
FROM Likes l
INNER JOIN Posts p ON p.postId = l.postId
INNER JOIN Polaroids pl ON pl.polaroidId = p.polaroidId
INNER JOIN photoCards pc ON pl.photocardId = pc.photocardId
INNER JOIN users u ON p.userId = u.userId
GROUP BY l.postId
ORDER BY likeQuant DESC
LIMIT 10;`;
con.query(sql, (err, result, fields)=>{
if(err) throw err;
const r={
hot10List:result
}
res.status(200).send(r);
})
})
//실시간도안
app.get('/mainpage/now5', verifyToken, async (req, res) => {
const sql = `
SELECT p.postId, pl.polaroid
FROM Posts p
INNER JOIN Polaroids pl ON p.polaroidId = pl.polaroidId
ORDER BY postId DESC
LIMIT 5;
`
con.query(sql, (err, result, fields)=>{
if(err) throw err;
const r = {
now5List: result // 여기에서 result는 변수명입니다. 원하는 결과 데이터로 대체되어야 합니다.
};
res.status(200).send(r);
console.log("실시간도안", result);
})
});
//랜덤 아티스트
app.get('/mainpage/randomArtist', verifyToken, async (req, res) => {
const sql = `SELECT DISTINCT enterComp FROM artists;`;
con.query(sql, (err, results, fields) => {
if (err) throw err;
const randomEnterComp = results[getRandomInt(results.length)].enterComp;
//console.log("소속사",randomEnterComp);
const sql2 = `SELECT artistId, groupName, photo
FROM artists
WHERE enterComp = ?`;
con.query(sql2, [randomEnterComp], (err, result, fields) => {
if (err) throw err;
const r = {
randomArtistList: result
};
res.status(200).send(r);
console.log("랜덤아티스트", result);
});
});
});
//artistpage
app.get('/artistpage/allArtist', verifyToken, async (req, res) => {
const sql1 = `SELECT enterComp FROM artists ORDER BY enterComp DESC`;
con.query(sql1, (err, result1) => {
if (err) throw err;
const enterComp = result1;
const allResults = [];
// 모든 비동기 쿼리가 완료될 때까지 대기하기 위한 카운터 변수
let queryCounter = 0;
for (let i = 0; i < enterComp.length; i++) {
const sql = `SELECT artistId, groupName, photo FROM artists WHERE enterComp = "${enterComp[i].enterComp}"`;
con.query(sql, (err, result) => {
if (err) throw err;
const r = {
enterComp: enterComp[i].enterComp,
artistList: result
};
allResults.push(r);
queryCounter++;
const resultSending = {
allArtistList: allResults
};
// 모든 쿼리가 완료되면 결과를 전송
if (queryCounter === enterComp.length) {
res.status(200).send(resultSending);
}
});
}
});
});
// 아티스트 프로필 조회
// const artistProfile = (artistId) => {
// return new Promise((resolve, reject) => {
// con.query(
// `SELECT
// artists.groupName,
// artists.photo,
// artists.enterComp,
// artists.collectionQuant
// FROM artists
// WHERE artists.artistId = ?
// ;`, [artistId], (err, result) => {
// if (err) {
// reject(err);
// } else {
// resolve(result[0]);
// }
// }
// );
// });
// };
// // 아티스트 즐겨찾기 수 조회
// const artistFavoriteQuant = (artistId) => {
// return new Promise((resolve, reject) => {
// con.query(
// `SELECT COUNT(*) AS favoriteQuant
// FROM Favorites
// WHERE artistId = ?; `, [artistId], (err, result) => {
// if (err) {
// reject(err);
// } else {
// resolve(result[0]);
// }
// }
// );
// });
// };
// app.get('/community/:artistId/artistProfile', async (req, res) => {
// const artistId = req.params.artistId;
// try {
// const profile = await artistProfile(artistId);
// const favoriteQuant = await artistFavoriteQuant(artistId);
// const result = {...profile, ...favoriteQuant};
// const r = {
// artistProfile: result
// };
// res.status(200).send(r);
// console.log('r', r);
// } catch (error) {
// console.error('에러:', error);
// res.status(500).send('내부 서버 오류');
// }
// });
// //아티스트 즐겨찾기 수 조회
// app.get('/community/:artistId/favoriteQuant', async (req, res) => {
// const artistId = req.params.artistId;
// const sql = `SELECT COUNT(*) AS favoriteQuant
// FROM Favorites
// WHERE artistId = ?; `;
// con.query(sql,[artistId], (err, result, fields)=>{
// if(err) throw err;
// const r = {
// ArtistFavoriteQuant: result[0]
// };
// res.status(200).send(r);
// //console.log("아티스트페이지", result);
// })
// });
// 아티스트 프로필 조회
app.get('/community/:artistId/artistProfile', verifyToken, async (req, res) => {
const artistId = req.params.artistId;
const sql = `SELECT
artists.groupName,
artists.photo,
artists.enterComp,
artists.collectionQuant
FROM artists
WHERE artists.artistId = ? `;
con.query(sql,[artistId], (err, result, fields)=>{
if(err) throw err;
const r = {
ArtistProfile: result[0]
};
res.status(200).send(r);
//console.log("아티스트페이지", result);
})
});
//아티스트 즐겨찾기 수 조회
app.get('/community/:artistId/favoriteQuant', verifyToken, async (req, res) => {
const artistId = req.params.artistId;
const sql = `SELECT COUNT(*) AS favoriteQuant
FROM Favorites
WHERE artistId = ?; `;
con.query(sql,[artistId], (err, result, fields)=>{
if(err) throw err;
// const r = {
// ArtistFavoriteQuant: result[0]
// };
res.status(200).send(result[0]);
});
});
//아티스트 즐겨찾기 해제
app.delete('/community/:artistId/notFavorite', verifyToken, async(req,res)=>{
const artistId = req.params.artistId;
const userId = req.decoded.userId;
const sql = `DELETE
FROM Favorites
WHERE (artistId=? AND userId=?);
`
con.query(sql, [artistId, userId], (err, result, fields)=>{
if(err) throw err;
res.status(200).send(result);
console.log(result);
})
});
//아티스트 내가 가진 컬렉션 조회
app.get('/community/:artistId/collectionQuant', verifyToken, async (req, res) => {
const userId = req.decoded.userId;
const artistId = req.params.artistId;
const sql = `SELECT COUNT(*) AS collectionQuant
FROM UserCollections uc
INNER JOIN collections c ON uc.albumName = c.albumName
WHERE uc.userId = ? AND c.artistId = ?; `;
con.query(sql,[userId, artistId], (err, result, fields)=>{
if(err) throw err;
// const r = {
// collectionQuantThatIHave: result[0]
// };
res.status(200).send(result[0]);
})
});
//멤버별 이름 및 사진 조회
app.get('/community/:artistId/members', verifyToken, async (req, res) => {
const artistId = req.params.artistId;
//const artistId = 1;
const sql = `SELECT
memberNum,
memberPhoto
FROM artists
WHERE artistId = ?; `;
con.query(sql, [artistId], (err, result, fields) => {
if(err) throw err;
if (result.length > 0) {
const memberNum = result[0].memberNum;
const memberPhoto = JSON.parse(result[0].memberPhoto); // memberPhoto는 배열이 아니라 ''문자열!!
console.log('memphoto',memberPhoto);
// const members = [];
// for (let i = 0; i < memberNum; i++) {
// const nameAndPhoto = {
// name: memberPhoto[i].name,
// memPhoto: memberPhoto[i].memPhoto
// };
// members.push(nameAndPhoto);
// }
const r = { memberPhoto }; // Wrap the members array in an object
res.status(200).send(r);
console.log("멤버별 이름과 사진", members);
} else {
res.status(404).send("No members found for the given artist ID.");
}
});
});
//아티스트 멤버별 도안 조회
app.get('/community/:memberName/memberPost', verifyToken, async (req, res) => {
const memberName =req.params.memberName;
// if(memberName=='아이유'){
// memberName = '아이유(IU)';
// }else{
// memberName=req.params.memberName;
// }
const sql = `SELECT
p.postId,
pl.polaroid,
pc.enterComp,
pc.groupName,
pc.memberName,
pc.albumName,
p.userId,
u.nickname
FROM Posts p
INNER JOIN users u ON p.userId = u.userId
INNER JOIN Polaroids pl ON p.polaroidId = pl.polaroidId
INNER JOIN photoCards pc ON pc.photocardId = pl.photocardId
WHERE pc.memberName = ?
ORDER BY p.postId DESC
; `;
con.query(sql, [memberName === '아이유' ? '아이유(IU)':memberName], async (err, result, fields) => {
if (err) throw err;
const finalResult = [];
for (let i = 0; i < result.length; i++) {
const postId = result[i].postId;
const sql2 = `SELECT l.postId, COUNT(*) AS likeQuant
FROM Likes l
WHERE l.postId = ?
GROUP BY l.postId
ORDER BY l.postId DESC`;
const likeQuantResult = await new Promise((resolve, reject) => {
con.query(sql2, [postId], (err, result, fields) => {
if (err) reject(err);
resolve(result.length > 0 ? result[0].likeQuant : 0);
// if (result.length > 0) {
// resolve(result[0].likeQuant);
// } else {
// resolve(0);
// }
//만약 결과가 있고, likeQuant 속성이 있다면 해당 값을 사용하고, 그렇지 않으면 기본값으로 0을 사용한다
});
});
const r = {
...result[i],
likeQuant: likeQuantResult
};
finalResult.push(r);
}
const r = {
memberPostList:finalResult
}
res.status(200).send(r);
});
});
// // 아티스트 멤버 별 도안 좋아요 수 조회
// app.get('/community/:memberName/memberPost/:postId/like', async(req, res)=>{
// const memberName = req.params.memberName;
// const postId = req.params.postId;
// const sql = `SELECT postId, COUNT(*) AS likeQuant
// FROM Likes
// WHERE postId = ?;`;
// con.query( sql, [postId], (err, result, fields)=>{
// if(err) throw err;
// const r = {
// postLikeQuantList: result
// }
// res.status(200).send(r);
// })
// });
//아티스트 전체 도안 조회
app.get('/community/:artistId/allPost', verifyToken, async (req, res) => {
const artistId = req.params.artistId;
const sql = `SELECT
p.postId,
pl.polaroid,
pc.enterComp,
pc.groupName,
pc.memberName,
pc.albumName,
p.userId,
u.nickname
FROM Posts p
INNER JOIN users u ON p.userId = u.userId
INNER JOIN Polaroids pl ON p.polaroidId = pl.polaroidId
INNER JOIN photoCards pc ON pc.photocardId = pl.photocardId
INNER JOIN artists a ON pc.enterComp = a.enterComp
WHERE a.artistId = ?
ORDER BY p.postId DESC; `
con.query(sql, [artistId], async (err, result, fields) => {
if (err) throw err;
const finalResult = [];
for (let i = 0; i < result.length; i++) {
const postId = result[i].postId;
const sql2 = `SELECT l.postId, COUNT(*) AS likeQuant
FROM Likes l
WHERE l.postId = ?
GROUP BY l.postId
ORDER BY l.postId DESC`;
const likeQuantResult = await new Promise((resolve, reject) => {
con.query(sql2, [postId], (err, result, fields) => {
if (err) reject(err);
resolve(result.length > 0 ? result[0].likeQuant : 0);
// if (result.length > 0) {
// resolve(result[0].likeQuant);
// } else {
// resolve(0);
// }
//만약 결과가 있고, likeQuant 속성이 있다면 해당 값을 사용하고, 그렇지 않으면 기본값으로 0을 사용한다
});
});
const r = {
...result[i],
likeQuant: likeQuantResult
};
finalResult.push(r);
}
const r = {
allPostList:finalResult
}
res.status(200).send(r);
});
});
// 아티스트 전체 도안 좋아요 수 조회
app.get('/community/:artistId/allPost/:postId/like', verifyToken, async(req, res)=>{
const artistId = req.params.artistId;
const postId = req.params.postId;
const sql = `SELECT postId, COUNT(*) AS likeQuant
FROM Likes
WHERE postId =?;`;
con.query( sql, [postId], (err, result, fields)=>{
if(err) throw err;
const r = {
allPostLikeQuantList: result
}
res.status(200).send(r);
})
});
// //도안 게시 - 컬렉션 선택
// app.get('/community/:userId/uploadPost/collection', async (req, res) => {
// const artistId = req.params.artistId;
// const sql = `SELECT
// memberNum,
// memberPhoto
// FROM artists
// WHERE artistId = ?; `;
// con.query(sql,[artistId], (err, result, fields)=>{
// if(err) throw err;
// const r = {
// memberNumandPhoto: result
// };
// res.status(200).send(r);
// //console.log("아티스트페이지", result);
// })
// });
// //도안 게시 - 도안 선택
// app.get('/community/:artistId/uploadPost/post', async (req, res) => {
// const artistId = req.params.artistId;
// const sql = `SELECT
// memberNum,
// memberPhoto
// FROM artists
// WHERE artistId = ?; `;
// con.query(sql,[artistId], (err, result, fields)=>{
// if(err) throw err;
// const r = {
// memberNumandPhoto: result
// };
// res.status(200).send(r);
// //console.log("아티스트페이지", result);
// })
// });
// 도안 게시(포스팅)
app.post('/community/uploadPost/:polaroidId/upload', verifyToken, async(req, res)=>{
let today = new Date();
let year = today.getFullYear(); // 년도
let month = today.getMonth() + 1; // 월
let date = today.getDate(); // 날짜
let nowdate = `${year}-${month}-${date}`;
let hours = today.getHours(); // 시
let minutes = today.getMinutes(); // 분
let seconds = today.getSeconds(); // 초
let time = `${hours}:${minutes}:${seconds}`;
let dateTime = `${nowdate} ${time}`;
//const image = `https://${process.env.BUCKET_NAME}.s3.${process.env.S3_REGION}.amazonaws.com/polaroid/${imgName}`;
const userId = req.decoded.userId;
const polaroidId = req.params.polaroidId;
const sql = `INSERT into Posts( postId, postDateTime, userId, polaroidId)
VALUES ( NULL, ?, ?, ?) `
con.query(sql, [ dateTime, userId, polaroidId ], (err, result, fields)=>{
if(err) throw err;
const msg = "포스팅 완료"
result.message = msg;
res.status(201).send(result);
console.log(result);
})
});
//mypage
//프로필 정보 조회
app.get('/mypage/myProfile', verifyToken, async(req, res)=>{
const userId = req.decoded.userId;
const sql = `SELECT userId, avatar, nickname, biography
FROM users
WHERE userId = ?
;`;
con.query(sql, [userId], (err, result, fields)=>{
if(err) throw err;
const r = {
userProfileInfo : result[0]
};
res.status(200).send(r);
console.log(result[0]);
})
});
//아티스트 탭 조회(포스트 유무 기준)
app.get('/mypage/myPost/artistTab', verifyToken, async(req, res)=>{
const userId = req.decoded.userId;
const sql = `SELECT DISTINCT pc.groupName, a.artistId
FROM Posts p
INNER JOIN Polaroids pl ON p.polaroidId = pl.polaroidId
INNER JOIN photoCards pc ON pl.photocardId = pc.photocardId
INNER JOIN artists a ON a.groupName = pc.groupName
WHERE p.userId = ?;
`;
con.query(sql, [userId], (err, result, fields)=>{
if(err) throw err;
result.forEach(item => {
item.groupName = item.groupName.replace(/\([^)]*\)/, '').trim();
});
const r = {
postArtistList: result
}
res.status(200).send(r);
})
});
//아티스트 별 포스트(게시 도안) 모아보기
app.get('/mypage/myPost/:artistId/post', verifyToken, async (req, res)=>{
const userId = req.decoded.userId;
const artistId = req.params.artistId;
const sql = `SELECT DISTINCT p.postId, p.postDateTime, pl.polaroid,
pc.enterComp, pc.groupName, pc.memberName, pc.albumName,
u.userId, u.nickname
FROM Posts p
INNER JOIN Polaroids pl ON pl.polaroidId = p.polaroidId
INNER JOIN photoCards pc ON pl.photocardId = pc.photocardId
INNER JOIN artists a ON a.groupName = pc.groupName
INNER JOIN users u ON p.userId = u.userId
WHERE p.userId = ? AND a.artistId=?
ORDER BY p.postId DESC;`;
con.query(sql, [userId, artistId], async (err, result, fields) => {
if (err) throw err;
const finalResult = [];
for (let i = 0; i < result.length; i++) {
const postId = result[i].postId;
const sql2 = `SELECT l.postId, COUNT(*) AS likeQuant
FROM Likes l
WHERE l.postId = ?
GROUP BY l.postId;`;
const likeQuantResult = await new Promise((resolve, reject) => {
con.query(sql2, [postId], (err, result, fields) => {
if (err) reject(err);
resolve(result.length > 0 ? result[0].likeQuant : 0);
// if (result.length > 0) {
// resolve(result[0].likeQuant);
// } else {
// resolve(0);
// }
//만약 결과가 있고, likeQuant 속성이 있다면 해당 값을 사용하고, 그렇지 않으면 기본값으로 0을 사용한다
});
});
const r = {
...result[i],
likeQuant: likeQuantResult
};
finalResult.push(r);
}
const r = {
myPostList:finalResult
}
res.status(200).send(r);
});
});
// //아티스트 별 게시 도안 좋아요 개수
// app.get('/mypage/:userId/myPost/:artistId/:postId/like', async(req, res)=>{
// const userId = req.params.userId;
// const artistId = req.params.artistId;
// const postId = req.params.postId;
// const sql = `SELECT COUNT(*) AS LikeQuant
// FROM Likes
// WHERE postId = ?;`;
// con.query(sql, [postId], (err, result, fields)=>{
// if(err) throw err;
// // const r = {
// // postOfArtistList: result
// // }
// res.status(200).send(result[0]);
// });
// });
//포스트 삭제하기
app.delete('/mypage/myPost/delete/:postId', verifyToken, async (req, res)=>{
const postId = req.params.postId;
const sql = `DELETE FROM Posts WHERE postId = ?;`;
con.query(sql, [postId], (err, result, fields)=>{
if(err) throw err;
const r = {
postDeleted: result
}
res.status(200).send(r);
console.log(r);
})
});
//아티스트 탭 정보 조회(즐겨찾기 기준)
app.get('/mypage/myCollection/artistTab', verifyToken, async (req, res)=>{
const userId = req.decoded.userId;
const sql = `SELECT f.artistId, a.groupName
FROM Favorites f
INNER JOIN artists a ON f.artistId = a.artistId
WHERE userId = ?;`;
con.query(sql, [userId], (err, result, fields)=>{
if(err) throw err;
result.forEach(item => {
item.groupName = item.groupName.replace(/\([^)]*\)/, '').trim();
});
const r = {
collectionArtistList: result
}
console.log(r);
res.status(200).send(r);
})
});
//활성화한 컬렉션 정보 조회
app.get('/mypage/myCollection/:artistId/active', verifyToken, async (req, res)=>{
const userId = req.decoded.userId;
const artistId = req.params.artistId;
const sql = `SELECT c.albumJacket, c.albumName, uc.activeDateTime, c.photoCardQuant
FROM collections c
INNER JOIN UserCollections uc ON uc.albumName = c.albumName
INNER JOIN users u ON u.userId = uc.userId
WHERE uc.userId = ? AND c.artistId = ?;`;
con.query(sql, [userId, artistId], (err, result, fields)=>{
if(err) throw err;
const r = {
activeCollectionList: result
}
res.status(200).send(r);
})
});
//전체 컬렉션 정보 조회
app.get('/mypage/myCollection/:artistId/allCollection', verifyToken, async(req, res)=>{
//const userId = req.params.userId;
const artistId = req.params.artistId;
const sql = `SELECT DISTINCT c.albumJacket, c.albumName
FROM collections c
WHERE c.artistId = ?;`;
con.query(sql, [artistId], (err, result, fields)=>{
if(err) throw err;
const r = {
allCollectionList: result
}
res.status(200).send(r);
})
});
//선택한 컬렉션 전체 포토카드 정보 조회
app.get('/mypage/myCollection/:albumName/allPhotocard', verifyToken, async (req, res)=>{
//const userId = req.params.userId;
//const artistId = req.params.artistId;
const albumName = req.params.albumName;
const sql = `SELECT pc.photocardId, pc.photocard, pc.version, pc.memberName
FROM collections c
INNER JOIN photoCards pc ON pc.albumName = c.albumName
WHERE c.albumName=?
ORDER BY pc.version;
`;
con.query(sql, [albumName], (err, result, fields)=>{
if(err) throw err;
const result1 = [];
const result2 = [];
const result3 = [];
for(let i=0;i<result.length; i++){
if(result[i].version === "a"){
result1.push(result[i]);
}else if(result[i].version === "b"){
result2.push(result[i]);
}else if(result[i].version === "c"){
result3.push(result[i]);
}
}
const r1 = {
verA: result1
}
const r2 = {
verB: result2
}
const r3 = {
verC: result3
}
const re = {
...r1, ...r2, ...r3
}
const r = {
collectionPhotocardList: re
}
res.status(200).send(r);
})
});
//선택한 컬렉션 활성화된 포토카드 정보 조회
app.get('/mypage/myCollection/:albumName/activePhotocard', verifyToken, async (req, res)=>{
const userId = req.decoded.userId;
//const artistId = req.params.artistId;
const albumName = req.params.albumName;
const sql = `SELECT upc.photocardId, pc.photocard, pc.version, pc.memberName
FROM UserPhotoCards upc
INNER JOIN photoCards pc ON pc.photocardId = upc.photocardId
WHERE upc.userId =? AND pc.albumName=?;`;
con.query(sql, [userId, albumName], (err, result, fields)=>{
if(err) throw err;
const r = {
ActivePhotocardList: result
}
res.status(200).send(r);
})
});
//아티스트 탭 정보 조회(도안이 하나라도 있는 경우)
app.get('/mypage/myPolaroid/artistTab', verifyToken, async(req, res)=>{
const userId = req.decoded.userId;
const sql = `SELECT DISTINCT a.artistId, a.groupName FROM artists a
INNER JOIN photoCards pc ON pc.enterComp = a.enterComp
INNER JOIN Polaroids pl ON pl.photocardId = pc.photocardId
WHERE pl.userUserId = ?`;
con.query(sql, [userId], (err, result, fields)=>{
if(err) throw err;
result.forEach(item => {
item.groupName = item.groupName.replace(/\([^)]*\)/, '').trim();
});
const r = {
polaroidArtistTabList: result
}
res.status(200).send(r);
})
});
//아티스트 별 활성화한 컬렉션 조회
app.get('/mypage/myPolaroid/:artistId/collection', verifyToken, async(req, res)=>{
const userId = req.decoded.userId;
const artistId = req.params.artistId;
const sql = `SELECT c.albumJacket, c.albumName
FROM collections c
INNER JOIN UserCollections uc ON uc.albumName = c.albumName
INNER JOIN users u ON u.userId = uc.userId
WHERE uc.userId = ? AND c.artistId = ?;`;
con.query(sql, [userId, artistId], (err, result, fields)=>{
if(err) throw err;
const r = {
collectionsList:result
}
res.status(200).send(r);
})
});
// 컬렉션 별 도안 개수 조회
app.get('/mypage/myPolaroid/:albumName/polaroidQuant', verifyToken, async(req, res)=>{
const userId = req.decoded.userId;
const albumName = req.params.albumName;