-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
1065 lines (904 loc) · 26.8 KB
/
app.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 * as dotenv from "dotenv"; // 환경 변수 로드
dotenv.config();
import express from "express";
import jwt from "jsonwebtoken";
import cors from "cors";
import { getChoseong } from "es-hangul";
import multer from "multer";
import sharp from "sharp";
import path from "path";
import { createClient } from "@supabase/supabase-js";
import { assert } from "superstruct"; // 데이터 검증을 위한 라이브러리
import {
CreateUser,
UpdateUser,
CreatePost,
UpdatePost,
CreateComment,
UpdateComment,
LikePost,
LikeComment,
} from "./lib/structs.js"; // Superstruct 스키마
import crypto from "crypto"; // 랜덤 문자열 생성을 위해 crypto 모듈 사용
import { prisma } from "./lib/prismaClient.js"; // PrismaClient 인스턴스
import { asyncHandler } from "./middleware/errorHandler.js"; // 에러 핸들러 미들웨어
const app = express();
app.use(
cors({
origin: [
"http://localhost:3000",
"https://localhost:3000",
"https://wjsdncl-dev-hub.vercel.app",
"https://www.wjdalswo-dev.xyz",
],
credentials: true,
})
);
app.use(express.json());
const JWT_SECRET = process.env.JWT_SECRET; // JWT 시크릿 키
const JWT_REFRESH_SECRET = process.env.JWT_REFRESH_SECRET; // RefreshToken을 위한 시크릿 키 설정
/* ========================
/
/
/ Auth API
/
/
======================== */
// JWT 토큰 생성 함수
function generateTokens(userId) {
const accessToken = jwt.sign({ userId }, JWT_SECRET, { expiresIn: "3d" }); // AccessToken 3일 만료
const refreshToken = jwt.sign({ userId }, JWT_REFRESH_SECRET, { expiresIn: "7d" }); // RefreshToken 7일 만료
return { accessToken, refreshToken };
}
const getCookies = (cookieString) => {
return cookieString.split("; ").reduce((acc, cookie) => {
const [key, value] = cookie.split("=");
acc[key] = value;
return acc;
}, {});
};
// 유저 인증 미들웨어
function requiredAuthenticate(req, res, next) {
const cookies = getCookies(req.headers.cookie);
const token = cookies.accessToken;
if (!token) return res.status(401).send({ message: "로그인이 필요합니다." });
jwt.verify(token, JWT_SECRET, (err, decoded) => {
if (err) {
// 액세스 토큰이 만료된 경우
if (err.name === "TokenExpiredError") {
const refreshToken = cookies.refreshToken;
if (!refreshToken) {
return res.status(401).send({ message: "세션이 만료되었습니다. 재로그인 해주세요." });
}
jwt.verify(refreshToken, JWT_REFRESH_SECRET, (err, decoded) => {
if (err) {
return res.status(401).send({ message: "세션이 만료되었습니다. 재로그인 해주세요." });
}
const { accessToken: newAccess, refreshToken: newRefresh } = generateTokens(
decoded.userId
);
// 새로운 토큰을 쿠키에 설정
res.cookie("accessToken", newAccess, {
httpOnly: true,
secure: true,
sameSite: "none",
});
res.cookie("refreshToken", newRefresh, {
httpOnly: true,
secure: true,
sameSite: "none",
});
req.user = decoded;
next();
});
} else {
return res.status(403).send({ message: "토큰이 유효하지 않거나 만료되었습니다." });
}
} else {
req.user = decoded;
next();
}
});
}
// 로그인 선택 미들웨어
function optionalAuthenticate(req, res, next) {
const cookies = getCookies(req.headers.cookie);
const token = cookies.accessToken;
if (!token) {
req.user = null;
return next();
}
jwt.verify(token, JWT_SECRET, (err, decoded) => {
req.user = err ? null : decoded;
next();
});
}
// POST /auth/signup -> 회원가입
app.post(
"/auth/signup",
asyncHandler(async (req, res) => {
const { email, name } = req.body;
assert({ email, name }, CreateUser);
// 이메일 중복 확인
const existingUser = await prisma.user.findUnique({ where: { email } });
if (existingUser) return res.status(409).send({ message: "이미 존재하는 사용자입니다." });
// 유저 생성
const newUser = await prisma.user.create({
data: {
email,
name,
},
});
res.status(201).send(newUser);
})
);
// POST /auth/login -> 로그인
app.post(
"/auth/login",
asyncHandler(async (req, res) => {
const { email } = req.body;
const user = await prisma.user.findUnique({ where: { email } });
if (!user) return res.status(401).send({ message: "사용자를 찾을 수 없습니다." });
const { accessToken, refreshToken } = generateTokens(user.id);
// JWT를 쿠키에 포함
res.cookie("accessToken", accessToken, {
httpOnly: true,
secure: true,
sameSite: "none",
});
// refreshToken을 secure 쿠키로 전송
res.cookie("refreshToken", refreshToken, {
httpOnly: true,
secure: true,
sameSite: "none",
});
res.send({ user });
})
);
// POST /auth/logout -> 로그아웃
app.post(
"/auth/logout",
asyncHandler(async (req, res) => {
res.clearCookie("accessToken");
res.clearCookie("refreshToken");
res.send({ message: "로그아웃 되었습니다." });
})
);
// POST /auth/refresh -> RefreshToken을 사용하여 AccessToken 갱신
app.post(
"/auth/refresh",
asyncHandler(async (req, res) => {
const cookies = getCookies(req.headers.cookie);
const refreshToken = cookies.refreshToken;
if (!refreshToken) {
return res.status(401).send({ message: "리프래시 토큰이 없습니다." });
}
jwt.verify(refreshToken, JWT_REFRESH_SECRET, (err, decoded) => {
if (err) return res.status(403).send({ message: "토큰이 유효하지 않습니다." });
const { accessToken: newAccess, refreshToken: newRefresh } = generateTokens(decoded.userId);
// JWT를 header에 포함
res.setHeader("Authorization", `Bearer ${newAccess}`);
// refreshToken을 secure 쿠키로 전송
res.cookie("refreshToken", newRefresh, {
httpOnly: true,
secure: true,
sameSite: "none",
});
res.send({ message: "토큰이 갱신되었습니다." });
});
})
);
/* ========================
/
/
/ User API
/
/
======================== */
// GET /users -> 모든 유저 정보를 가져옴
app.get(
"/users",
requiredAuthenticate, // JWT 인증
asyncHandler(async (req, res) => {
const { offset = 0, limit = 10 } = req.query; // 페이지네이션을 위한 쿼리 파라미터
const users = await prisma.user.findMany({
skip: parseInt(offset),
take: parseInt(limit),
orderBy: { createdAt: "desc" }, // 최신 순으로 정렬
select: {
id: true,
email: true,
name: true,
createdAt: true,
updatedAt: true,
_count: { select: { posts: true, comments: true } }, // 게시글 및 댓글 수 포함
posts: { select: { category: true, title: true, content: true } }, // 유저가 작성한 포스트 정보 포함
},
});
res.send(users);
})
);
// GET /users/me -> accessToken을 사용하여 현재 유저 정보를 가져옴
app.get(
"/users/me",
requiredAuthenticate,
asyncHandler(async (req, res) => {
const user = await prisma.user.findUnique({
where: { id: req.user.userId },
select: {
id: true,
email: true,
name: true,
createdAt: true,
updatedAt: true,
isAdmin: true,
posts: {
select: {
_count: { select: { comments: true } },
category: true,
id: true,
title: true,
createdAt: true,
},
},
comments: {
select: {
id: true,
content: true,
createdAt: true,
},
},
},
});
if (!user) {
return res.status(404).send({ error, message: "유저 정보를 찾을 수 없습니다." });
}
res.send(user);
})
);
// PATCH /users/:id -> 특정 유저 정보를 수정
app.patch(
"/users/:id",
requiredAuthenticate, // JWT 인증
asyncHandler(async (req, res) => {
assert({ email: req.body.email, name: req.body.name }, UpdateUser); // 유효성 검사
const { id } = req.params;
const user = await prisma.user.update({
where: { id },
data: req.body,
});
res.send(user);
})
);
// DELETE /users/:id -> 특정 유저 정보를 삭제
app.delete(
"/users/:id",
requiredAuthenticate, // JWT 인증
asyncHandler(async (req, res) => {
const { id } = req.params;
await prisma.user.delete({
where: { id },
});
res.status(204).send();
})
);
/* ========================
/
/
/ Post API
/
/
======================== */
// GET /posts -> 모든 포스트 정보를 가져옴
app.get(
"/posts",
asyncHandler(async (req, res) => {
const {
offset = 0,
limit = 10,
order = "newest",
category = "",
tag = "",
search = "",
} = req.query;
let orderBy;
switch (order) {
case "oldest":
orderBy = { createdAt: "asc" };
break;
case "newest":
orderBy = { createdAt: "desc" };
break;
case "like":
orderBy = { likes: "desc" };
break;
default:
orderBy = { createdAt: "desc" };
}
// 검색 조건 설정
const where = {
...(category && { category }),
...(tag && { tags: { has: tag } }),
...(search && {
choseongTitle: {
contains: getChoseong(search).replace(/\s+/g, ""),
mode: "insensitive",
},
}),
};
// 비동기 작업들을 병렬로 실행
const [totalPosts, allCategoryCounts, posts] = await Promise.all([
// 전체 포스트 개수 계산
prisma.post.count(),
// 카테고리 카운트 계산
prisma.post.groupBy({
by: ["category"],
_count: { category: true },
}),
// 포스트 가져오기
prisma.post.findMany({
where,
orderBy,
skip: parseInt(offset),
take: parseInt(limit),
include: { _count: { select: { comments: true } } },
}),
]);
const categoryCounts = allCategoryCounts.reduce((acc, curr) => {
if (curr.category && curr.category.trim() !== "") {
acc[curr.category] = curr._count.category;
}
return acc;
}, {});
res.send({
totalPosts,
categoryCounts,
posts,
});
})
);
// GET /posts/:title -> 특정 포스트 정보를 가져옴
app.get(
"/posts/:title",
optionalAuthenticate, // JWT 인증 (선택적)
asyncHandler(async (req, res) => {
const { title } = req.params;
const userId = req.user?.userId;
const post = await prisma.post.findUniqueOrThrow({
where: { slug: title },
include: {
user: { select: { id: true, email: true, name: true } },
_count: { select: { comments: true, Like: true } },
},
});
post.isLiked = false;
// 로그인된 유저일 경우에만 좋아요 여부를 검사
if (userId) {
const existingLike = await prisma.like.findUnique({
where: {
userId_postId: { userId, postId: post.id },
},
});
post.isLiked = !!existingLike;
}
res.send(post);
})
);
// POST /posts -> 포스트 정보를 생성
app.post(
"/posts",
requiredAuthenticate, // JWT 인증
asyncHandler(async (req, res) => {
const { title, content, userId, coverImg, category, tags = [] } = req.body;
assert(req.body, CreatePost);
// 고유한 슬러그 생성
let slugBase = title
.toLowerCase()
.trim()
.replace(/-/g, "") // 하이픈 제거
.replace(/\s+/g, "-") // 공백을 하이픈으로
.replace(/[^a-z0-9가-힣ㄱ-ㅎ-]/g, ""); // 특수문자 제거
let slug = `${slugBase}`;
while (await prisma.post.findUnique({ where: { slug } })) {
slug = `${slugBase}-${crypto.randomBytes(2).toString("hex").slice(0, 3)}`;
}
const choseongTitle = getChoseong(title).replace(/\s+/g, "");
const newPost = await prisma.post.create({
data: {
title,
choseongTitle,
content,
slug,
coverImg: coverImg === "" ? null : coverImg,
category: category === "" ? null : category,
tags,
user: { connect: { id: userId } },
},
include: {
user: { select: { email: true, name: true } },
},
});
res.status(201).send(newPost);
})
);
// POST /posts/:id/like -> 특정 포스트에 좋아요를 누름
app.post(
"/posts/:id/like",
requiredAuthenticate, // JWT 인증
asyncHandler(async (req, res) => {
const { id } = req.params;
const userId = req.user.userId;
const postId = parseInt(id);
assert({ userId, postId }, LikePost); // 유효성 검사
// 트랜잭션을 사용하여 좋아요 처리와 포스트 업데이트를 원자적으로 수행
const result = await prisma.$transaction(async (prisma) => {
// 유저가 해당 포스트에 좋아요를 눌렀는지 확인
const existingLike = await prisma.like.findUnique({
where: {
userId_postId: { userId, postId },
},
});
let isLike;
let updatedPost;
if (existingLike) {
// 좋아요 취소
await prisma.like.delete({
where: {
userId_postId: { userId, postId },
},
});
updatedPost = await prisma.post.update({
where: { id: postId },
data: { likes: { decrement: 1 } },
select: { id: true, title: true, likes: true },
});
isLike = false;
} else {
// 좋아요 추가
await prisma.like.create({
data: {
userId,
postId,
},
});
updatedPost = await prisma.post.update({
where: { id: postId },
data: { likes: { increment: 1 } },
select: { id: true, title: true, likes: true },
});
isLike = true;
}
return { updatedPost, isLike };
});
res.send({ post: result.updatedPost, isLike: result.isLike });
})
);
// PATCH /posts/:id -> 특정 포스트 정보를 수정
app.patch(
"/posts/:id",
requiredAuthenticate, // JWT 인증
asyncHandler(async (req, res) => {
const { title } = req.body;
assert(req.body, UpdatePost); // 유효성 검사
const id = Number(req.params.id);
// 게시글 제목 수정 시, 슬러그도 수정
const existingPost = await prisma.post.findUnique({
where: { id },
select: { slug: true, title: true },
});
let slug;
if (title && title !== existingPost.title) {
let slugBase = title
.toLowerCase()
.trim()
.replace(/-/g, "") // 하이픈 제거
.replace(/\s+/g, "-") // 공백을 하이픈으로
.replace(/[^a-z0-9가-힣ㄱ-ㅎ-]/g, "");
slug = `${slugBase}`;
while (await prisma.post.findFirst({ where: { slug } })) {
slug = `${slugBase}-${crypto.randomBytes(2).toString("hex").slice(0, 3)}`;
}
} else {
slug = existingPost.slug;
}
const choseongTitle = title ? getChoseong(title).replace(/\s+/g, "") : undefined;
const post = await prisma.post.update({
where: { id },
data: {
...req.body,
...(choseongTitle && { choseongTitle }),
...(slug && { slug }),
},
});
res.send(post);
})
);
// DELETE /posts/:id -> 특정 포스트 정보를 삭제
app.delete(
"/posts/:id",
requiredAuthenticate, // JWT 인증
asyncHandler(async (req, res) => {
const id = Number(req.params.id);
await prisma.post.delete({
where: { id },
});
res.status(204).send();
})
);
/* ========================
/
/
/ Comment API
/
/
======================== */
// GET /comments -> 모든 댓글 정보를 가져옴
app.get(
"/comments",
asyncHandler(async (req, res) => {
const { offset = 0, limit = 10 } = req.query;
const comments = await prisma.comment.findMany({
skip: parseInt(offset),
take: parseInt(limit),
orderBy: { createdAt: "desc" },
include: {
post: { select: { title: true } },
user: { select: { email: true, name: true } },
replies: { include: { user: { select: { email: true, name: true } } } },
},
});
res.send(comments);
})
);
// GET /comments/:postID -> 특정 포스트의 댓글 정보를 가져옴
app.get(
"/comments/:postId",
optionalAuthenticate, // JWT 인증 (선택적)
asyncHandler(async (req, res) => {
const { offset = 0, limit = 10 } = req.query;
const { postId } = req.params;
const userId = req.user?.userId;
const post = await prisma.post.findUniqueOrThrow({
where: { id: parseInt(postId) },
select: { id: true },
});
const totalComments = await prisma.comment.count({
where: { postId: post.id },
});
const parentComments = await prisma.comment.count({
where: { postId: post.id, parentCommentId: null },
});
const includeReplies = (depth = 10) => ({
include:
depth > 0
? {
user: { select: { email: true, name: true } },
replies: {
include: {
user: { select: { email: true, name: true } },
replies: includeReplies(depth - 1),
_count: { select: { CommentLike: true } },
},
},
_count: { select: { CommentLike: true } },
}
: {
user: { select: { email: true, name: true } },
_count: { select: { CommentLike: true } },
},
});
const comments = await prisma.comment.findMany({
skip: parseInt(offset),
take: parseInt(limit),
orderBy: { createdAt: "desc" },
where: { postId: post.id, parentCommentId: null },
...includeReplies(),
});
const checkLikes = async (comment) => {
let isLiked = false;
// 로그인된 유저일 경우에만 좋아요 여부를 검사
if (userId) {
const existingLike = await prisma.commentLike.findUnique({
where: {
userId_commentId: { userId, commentId: comment.id },
},
});
isLiked = !!existingLike;
}
const repliesWithLikes = comment.replies
? await Promise.all(comment.replies.map(checkLikes))
: [];
return {
...comment,
isLiked,
replies: repliesWithLikes,
};
};
const commentsWithLikes = await Promise.all(comments.map(checkLikes));
res.send({ totalComments, parentComments, comments: commentsWithLikes });
})
);
// POST /comments -> 댓글 또는 대댓글 작성
app.post(
"/comments",
requiredAuthenticate,
asyncHandler(async (req, res) => {
assert(req.body, CreateComment); // 유효성 검사
const { content, userId, postId, parentCommentId } = req.body;
const newComment = await prisma.comment.create({
data: {
content,
user: userId ? { connect: { id: userId } } : undefined,
post: { connect: { id: postId } },
parentComment: parentCommentId ? { connect: { id: parentCommentId } } : undefined, // 대댓글인 경우
},
});
res.status(201).send(newComment);
})
);
// POST /comments/:id/like -> 특정 댓글에 좋아요를 누름
app.post(
"/comments/:id/like",
requiredAuthenticate, // JWT 인증
asyncHandler(async (req, res) => {
const { id } = req.params;
const userId = req.user.userId;
const commentId = parseInt(id);
assert({ userId, commentId }, LikeComment); // 유효성 검사
// 유저가 해당 댓글에 좋아요를 눌렀는지 확인
const existingLike = await prisma.commentLike.findUnique({
where: {
userId_commentId: { userId, commentId },
},
});
let isLike; // 좋아요 상태를 나타낼 boolean 변수
const updateData = existingLike
? { likes: { decrement: 1 } } // 좋아요 취소
: { likes: { increment: 1 } }; // 좋아요 추가
// 좋아요를 토글 처리
if (existingLike) {
await prisma.commentLike.delete({
where: {
userId_commentId: { userId, commentId },
},
});
isLike = false; // 좋아요 취소
} else {
await prisma.commentLike.create({
data: {
userId,
commentId,
},
});
isLike = true; // 좋아요 추가
}
// 업데이트 후 댓글 데이터에서 필요한 필드만 선택해서 응답
const updatedComment = await prisma.comment.update({
where: { id: commentId },
data: updateData,
select: { id: true, content: true, likes: true }, // 필요한 필드만 선택
});
res.send({
comment: updatedComment, // 필요한 필드만 전송
isLike, // 좋아요 상태 전송
});
})
);
// PATCH /comments/:id -> 특정 댓글을 수정
app.patch(
"/comments/:id",
requiredAuthenticate, // JWT 인증
asyncHandler(async (req, res) => {
assert(req.body, UpdateComment); // 유효성 검사
const id = Number(req.params.id);
const comment = await prisma.comment.update({
where: { id },
data: req.body,
});
res.send(comment);
})
);
// DELETE /comments/:id -> 댓글 삭제
app.delete(
"/comments/:id",
requiredAuthenticate, // JWT 인증
asyncHandler(async (req, res) => {
const { id } = req.params;
// 삭제할 댓글이 존재하는지 확인
const comment = await prisma.comment.findUnique({
where: { id: parseInt(id) },
include: {
replies: true,
},
});
if (!comment) {
return res.status(404).send({ message: "댓글을 찾을 수 없습니다." });
}
// 댓글에 답글이 있는지 확인
if (comment.replies.length > 0) {
// 답글이 있을 경우, 내용만 지우고 구조 유지
await prisma.comment.update({
where: { id: parseInt(id) },
data: {
content: "[삭제된 댓글입니다]", // 댓글 내용 삭제
likes: 0, // 좋아요 수 초기화
userId: null, // 유저 정보 삭제
},
});
} else {
// 답글이 없을 경우, 댓글을 완전히 삭제
await prisma.comment.delete({
where: { id: parseInt(id) },
});
}
res.status(204).send();
})
);
/* ========================
/
/
/ File Upload API
/
/
======================== */
// Supabase 클라이언트 생성
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY);
// 허용된 이미지 파일 형식
const ALLOWED_MIME_TYPES = {
"image/jpeg": ".jpg",
"image/png": ".png",
"image/gif": ".gif",
"image/webp": ".webp",
};
// Multer 설정 (파일 업로드 미들웨어)
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 5 * 1024 * 1024, files: 1 },
fileFilter: (req, file, cb) => {
if (ALLOWED_MIME_TYPES[file.mimetype]) {
cb(null, true);
} else {
cb(new Error("허용된 이미지 파일 형식만 업로드할 수 있습니다."), false);
}
},
});
// 이미지 처리 및 Supabase에 업로드 함수
async function processAndUploadImage(buffer, originalName) {
const baseName = path.basename(originalName, path.extname(originalName));
const filename = `${Date.now()}-${baseName}.webp`;
// 이미지 메타데이터를 읽어서 원본 크기 확인
const metadata = await sharp(buffer).metadata();
const { width: originalWidth, height: originalHeight } = metadata;
// 가로/세로 비율에 따라 리사이징 옵션 설정
let resizeOptions;
if (originalWidth >= originalHeight) {
// 가로가 더 길거나 같은 경우
resizeOptions = {
width: 1280,
height: Math.round((1280 * originalHeight) / originalWidth),
};
} else {
// 세로가 더 긴 경우
resizeOptions = {
width: Math.round((1280 * originalWidth) / originalHeight),
height: 1280,
};
}
const resizedBuffer = await sharp(buffer)
.resize(resizeOptions.width, resizeOptions.height, {
fit: "inside",
withoutEnlargement: true,
})
.webp({ quality: 90 })
.toBuffer();
const { data, error } = await supabase.storage
.from("images")
.upload(filename, resizedBuffer, { contentType: "image/webp" });
if (error) throw new Error(`이미지 업로드 중 에러 발생: ${error.message}`);
const result = supabase.storage.from("images").getPublicUrl(data.path);
return result.data.publicUrl;
}
// POST /upload -> 이미지 업로드 API
app.post(
"/upload",
requiredAuthenticate,
upload.single("file"),
asyncHandler(async (req, res) => {
if (!req.file) {
return res.status(400).json({ success: false, error: "이미지 파일을 업로드하세요." });
}
// HD 해상도로 이미지 처리 및 업로드
const url = await processAndUploadImage(req.file.buffer, req.file.originalname);
res.send({
success: true,
url,
});
})
);
/* ========================
/
/
/ Portfolio API
/
/
======================== */
// GET /projects -> 모든 프로젝트 정보 가져오기
app.get(
"/projects",
asyncHandler(async (req, res) => {
const projects = await prisma.project.findMany({
orderBy: { createdAt: "desc" },
});
res.send(projects);
})
);
// GET /projects/:id -> 특정 프로젝트 정보 가져오기
app.get(
"/projects/:id",
asyncHandler(async (req, res) => {
const { id } = req.params;
const project = await prisma.project.findUniqueOrThrow({
where: { id: Number(id) },
});
res.send(project);
})
);
// POST /projects -> 새로운 프로젝트 생성
app.post(
"/projects",