-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
77 lines (67 loc) · 2.14 KB
/
route.ts
File metadata and controls
77 lines (67 loc) · 2.14 KB
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
import { NextRequest } from 'next/server';
import dbConnect from '@/app/lib/dbConnect';
import View from '@/app/models/View';
export const POST = async (request: Request) => {
const { postId, referrer } = await request.json();
const fingerprint = request.headers.get('X-Fingerprint') || '';
if (!postId) {
return new Response('postId가 필요합니다.', { status: 400 });
}
if (!fingerprint) {
return new Response('Fingerprint가 필요합니다.', { status: 400 });
}
await dbConnect();
const existingLike = await View.findOne({ postId, fingerprint });
if (existingLike) {
if (!existingLike.referrer && referrer) {
await View.updateOne({ _id: existingLike._id }, { referrer });
}
const viewCount = await View.countDocuments({ postId });
return Response.json(
{ message: '이미 조회한 유저입니다.', viewCount },
{ status: 203 }
);
} else {
const result = await View.create({
postId,
fingerprint,
referrer: referrer || '',
});
const viewCount = await View.countDocuments({ postId });
if (result) {
return Response.json(
{ message: '조회수 증가 성공', viewCount },
{ status: 200 }
);
} else {
return Response.json(
{ message: '조회수 증가 실패', viewCount },
{ status: 500 }
);
}
}
};
export const GET = async (request: NextRequest) => {
try {
const postId = request.nextUrl.searchParams.get('postId') || '';
const fingerprint = request.headers.get('X-Fingerprint') || '';
if (!postId) {
return new Response('postId가 필요합니다.', { status: 400 });
}
if (!fingerprint) {
return new Response('Fingerprint가 필요합니다.', { status: 400 });
}
await dbConnect();
const viewCount = (await View.countDocuments({ postId })) || 0;
return Response.json(
{
viewCount: viewCount,
message: '조회수 가져오기 성공',
},
{ status: 200 }
);
} catch (error) {
console.error('조회수 가져오기 오류:', error);
return new Response('조회수 가져오기 실패', { status: 500 });
}
};