Skip to content

Commit feeb4ff

Browse files
committed
♻️ Refactor API Routing Codes to .ts
1 parent a819ddb commit feeb4ff

File tree

8 files changed

+277
-266
lines changed

8 files changed

+277
-266
lines changed
File renamed without changes.
Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,30 @@
11
// api/answers/[answerID]
22

3-
import { PrismaClient } from "@prisma/client";
4-
import { NextResponse } from "next/server";
3+
import { PrismaClient } from '@prisma/client';
4+
import { NextApiRequest } from 'next';
5+
import { NextResponse } from 'next/server';
56

67
const prisma = new PrismaClient();
78

8-
export async function GET(request, { params }) {
9-
// 답변 ID를 받아
10-
// 답변 데이터를 보내주기
9+
export async function GET(
10+
request: NextApiRequest,
11+
{ params }: { params: { answerID: string } }
12+
) {
13+
// 답변 ID를 받아
14+
// 답변 데이터를 보내주기
1115

12-
const answerID = params.answerID;
16+
const answerID = params.answerID;
1317

14-
// ID를 통해 Doc 불러오기
15-
const data = await prisma.answer.findUnique({
16-
where: {
17-
id: answerID,
18-
},
19-
});
18+
// ID를 통해 Doc 불러오기
19+
const data = await prisma.answer.findUnique({
20+
where: {
21+
id: answerID,
22+
},
23+
});
2024

21-
if (data !== null) {
22-
return NextResponse.json(data);
23-
} else {
24-
return NextResponse.json("NO DATA", { status: 404 });
25-
}
25+
if (data !== null) {
26+
return NextResponse.json(data);
27+
} else {
28+
return NextResponse.json('NO DATA', { status: 404 });
29+
}
2630
}
Lines changed: 54 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,62 @@
11
// api/answers/byarticle/[articleID]
22

3-
import { NextResponse } from "next/server";
4-
import { getServerSession } from "next-auth";
5-
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
6-
import { PrismaClient } from "@prisma/client";
3+
import { NextResponse } from 'next/server';
4+
import { getServerSession } from 'next-auth';
5+
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
6+
import { PrismaClient } from '@prisma/client';
7+
import { NextApiRequest } from 'next';
78

89
const prisma = new PrismaClient();
910

10-
export async function GET(request, { params }) {
11-
// 게시물 ID를 받아서
12-
// 게시물의 답변 현황과 (예 / 아니오 숫자)
13-
// 사용자의 답변 현황 ID 보내주기
14-
15-
const session = await getServerSession(authOptions);
16-
17-
const articleID = params.articleID;
18-
19-
const answers = await prisma.answer.findMany({
20-
where: {
21-
articleId: articleID,
22-
},
11+
export async function GET(
12+
request: NextApiRequest,
13+
{ params }: { params: { articleID: string } }
14+
) {
15+
// 게시물 ID를 받아서
16+
// 게시물의 답변 현황과 (예 / 아니오 숫자)
17+
// 사용자의 답변 현황 ID 보내주기
18+
19+
const session = await getServerSession(authOptions);
20+
21+
const articleID = params.articleID;
22+
23+
const answers = await prisma.answer.findMany({
24+
where: {
25+
articleId: articleID,
26+
},
27+
});
28+
29+
const data: { [key: string]: number } = {};
30+
let yourResponse = undefined;
31+
let pointSum = 0;
32+
33+
if (session) {
34+
answers.forEach((answer) => {
35+
pointSum += answer.cost;
36+
if (data[answer.answerVal]) {
37+
data[answer.answerVal]++;
38+
} else {
39+
data[answer.answerVal] = 1;
40+
}
41+
if (answer.userId === session.user?.id) {
42+
// 현재 세션의 답변
43+
yourResponse = [answer.id, answer.answerVal];
44+
}
2345
});
24-
25-
const data = {};
26-
let yourResponse = undefined;
27-
let pointSum = 0;
28-
29-
if (session) {
30-
answers.forEach((answer) => {
31-
pointSum += answer.cost;
32-
if (data[answer.answerVal]) {
33-
data[answer.answerVal]++;
34-
} else {
35-
data[answer.answerVal] = 1;
36-
}
37-
if (answer.userId === session.user?.id) {
38-
// 현재 세션의 답변
39-
yourResponse = [answer.id, answer.answerVal];
40-
}
41-
});
42-
} else {
43-
answers.forEach((answer) => {
44-
if (data[answer.answerVal]) {
45-
data[answer.answerVal]++;
46-
} else {
47-
data[answer.answerVal] = 1;
48-
}
49-
});
50-
}
51-
52-
return NextResponse.json({
53-
data,
54-
yourResponse,
55-
pointSum,
56-
totalNum: answers.length,
46+
} else {
47+
answers.forEach((answer) => {
48+
if (data[answer.answerVal]) {
49+
data[answer.answerVal]++;
50+
} else {
51+
data[answer.answerVal] = 1;
52+
}
5753
});
54+
}
55+
56+
return NextResponse.json({
57+
data,
58+
yourResponse,
59+
pointSum,
60+
totalNum: answers.length,
61+
});
5862
}

src/app/api/answers/route.ts

Lines changed: 74 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -1,98 +1,98 @@
11
// api/answers
22

3-
import { getServerSession } from "next-auth";
4-
import { NextResponse } from "next/server";
5-
import { authOptions } from "../auth/[...nextauth]/route";
6-
import { PrismaClient } from "@prisma/client";
3+
import { getServerSession } from 'next-auth';
4+
import { NextResponse } from 'next/server';
5+
import { authOptions } from '../auth/[...nextauth]/route';
6+
import { PrismaClient } from '@prisma/client';
77

88
const prisma = new PrismaClient();
99

10-
export async function POST(request) {
11-
// request로부터 받은 데이터 서버에 추가
10+
export async function POST(request: Request) {
11+
// request로부터 받은 데이터 서버에 추가
1212

13-
// COST ::
14-
// 사용자의 궁예지수가 충분할 때, 답변 가능한 로직
13+
// COST ::
14+
// 사용자의 궁예지수가 충분할 때, 답변 가능한 로직
1515

16-
const reqData = await request.json();
16+
const reqData = await request.json();
1717

18-
const answerVal = reqData.answerVal;
19-
const articleID = reqData.article;
18+
const answerVal = reqData.answerVal;
19+
const articleID = reqData.article;
2020

21-
const session = await getServerSession(authOptions);
21+
const session = await getServerSession(authOptions);
2222

23-
if (session) {
24-
// 사용자가 정상적으로 로그인 했을 때
25-
const sessionID = session.user?.id;
26-
const article = await prisma.article.findUnique({
27-
where: {
28-
id: articleID,
23+
if (session) {
24+
// 사용자가 정상적으로 로그인 했을 때
25+
const sessionID = session.user?.id;
26+
const article = await prisma.article.findUnique({
27+
where: {
28+
id: articleID,
29+
},
30+
});
31+
if (article !== null) {
32+
// 아티클이 존재할 때
33+
if (sessionID !== article.userId) {
34+
// 아티클의 작성자와 답변자가 다를 때 DB 등록
35+
try {
36+
await prisma.answer.create({
37+
data: {
38+
answerVal,
39+
articleId: articleID,
40+
userId: sessionID,
41+
postingDate: new Date().toISOString(),
42+
cost: 1,
2943
},
30-
});
31-
if (article !== null) {
32-
// 아티클이 존재할 때
33-
if (sessionID !== article.userId) {
34-
// 아티클의 작성자와 답변자가 다를 때 DB 등록
35-
try {
36-
await prisma.answer.create({
37-
data: {
38-
answerVal,
39-
articleId: articleID,
40-
userId: sessionID,
41-
postingDate: new Date().toISOString(),
42-
cost: 1,
43-
},
44-
});
45-
} catch (err) {
46-
return NextResponse.json("서버에 데이터 추가 중 오류", {
47-
status: 500,
48-
});
49-
}
50-
return NextResponse.json("Done It");
51-
} else {
52-
return NextResponse.json("403 오류", {
53-
status: 403,
54-
});
55-
}
56-
} else {
57-
return NextResponse.json("아티클이 존재하지 않습니다", {
58-
status: 404,
59-
});
44+
});
45+
} catch (err) {
46+
return NextResponse.json('서버에 데이터 추가 중 오류', {
47+
status: 500,
48+
});
6049
}
50+
return NextResponse.json('Done It');
51+
} else {
52+
return NextResponse.json('403 오류', {
53+
status: 403,
54+
});
55+
}
6156
} else {
62-
return NextResponse.json("세션이 존재하지 않습니다", { status: 401 });
57+
return NextResponse.json('아티클이 존재하지 않습니다', {
58+
status: 404,
59+
});
6360
}
61+
} else {
62+
return NextResponse.json('세션이 존재하지 않습니다', { status: 401 });
63+
}
6464
}
6565

66-
export async function DELETE(request) {
67-
// 답변 ID를 받아
68-
// 해당 답변을 세션이 맞다면 지우기
66+
export async function DELETE(request: Request) {
67+
// 답변 ID를 받아
68+
// 해당 답변을 세션이 맞다면 지우기
6969

70-
const reqData = await request.json();
71-
const answerID = reqData.id;
70+
const reqData = await request.json();
71+
const answerID = reqData.id;
7272

73-
const session = await getServerSession(authOptions);
73+
const session = await getServerSession(authOptions);
7474

75-
const answer = await prisma.answer.findUnique({
75+
const answer = await prisma.answer.findUnique({
76+
where: {
77+
id: answerID,
78+
},
79+
});
80+
81+
if (answer !== null) {
82+
// id에 해당하는 답변 존재
83+
if (answer.userId === session?.user?.id) {
84+
// 답변 작성자와 세션 이메일이 같을 때 삭제 진행
85+
await prisma.answer.delete({
7686
where: {
77-
id: answerID,
87+
id: answerID,
7888
},
79-
});
80-
81-
if (answer !== null) {
82-
// id에 해당하는 답변 존재
83-
if (answer.userId === session.user?.id) {
84-
// 답변 작성자와 세션 이메일이 같을 때 삭제 진행
85-
await prisma.answer.delete({
86-
where: {
87-
id: answerID,
88-
},
89-
});
90-
}
91-
} else {
92-
return NextResponse.json("해당 ID의 답변이 존재하지 않습니다", {
93-
status: 404,
94-
});
89+
});
9590
}
91+
} else {
92+
return NextResponse.json('해당 ID의 답변이 존재하지 않습니다', {
93+
status: 404,
94+
});
95+
}
9696

97-
return NextResponse.json({ answerID });
97+
return NextResponse.json({ answerID });
9898
}

0 commit comments

Comments
 (0)