Skip to content

Commit 6beeb44

Browse files
committed
Refactor out routes for Client Components
Also cleaned up code with Prettier formatter.
1 parent a7b89d9 commit 6beeb44

File tree

13 files changed

+224
-174
lines changed

13 files changed

+224
-174
lines changed

peerprep/api/gateway.ts

Lines changed: 28 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,29 @@
11
import { cookies } from "next/headers";
2-
import {
3-
Question,
4-
StatusBody,
5-
QuestionFullBody,
6-
LoginResponse,
7-
SigninResponse,
8-
} from "./structs";
2+
import { Question, StatusBody, LoginResponse, SigninResponse } from "./structs";
93

10-
function generateJSONHeaders() {
4+
export function generateAuthHeaders() {
115
return {
6+
Authorization: `Bearer ${cookies().get("session")}`,
7+
};
8+
}
9+
10+
export function generateJSONHeaders() {
11+
return {
12+
...generateAuthHeaders(),
1213
"Content-type": "application/json; charset=UTF-8",
13-
"Authorization": `Bearer ${cookies().get("session")}`
14-
}
14+
};
1515
}
1616

1717
export async function fetchQuestion(
1818
questionId: string
1919
): Promise<Question | StatusBody> {
2020
try {
2121
const response = await fetch(
22-
`${process.env.NEXT_PUBLIC_QUESTION_SERVICE}/questions/solve/${questionId}`
22+
`${process.env.NEXT_PUBLIC_QUESTION_SERVICE}/questions/solve/${questionId}`,
23+
{
24+
method: "GET",
25+
headers: generateAuthHeaders(),
26+
}
2327
);
2428
if (!response.ok) {
2529
return {
@@ -33,91 +37,21 @@ export async function fetchQuestion(
3337
}
3438
}
3539

36-
export async function addQuestion(body: QuestionFullBody): Promise<StatusBody> {
40+
export async function getSessionLogin(validatedFields: {
41+
email: string;
42+
password: string;
43+
}): Promise<LoginResponse | StatusBody> {
3744
try {
38-
const response = await fetch(
39-
`${process.env.NEXT_PUBLIC_QUESTION_SERVICE}/questions`,
45+
const res = await fetch(
46+
`${process.env.NEXT_PUBLIC_USER_SERVICE}/auth/login`,
4047
{
4148
method: "POST",
42-
body: JSON.stringify(body).replace(
43-
/(\"difficulty\":)\"([1-3])\"/,
44-
`$1$2`
45-
),
46-
headers: {
47-
"Content-type": "application/json; charset=UTF-8",
48-
},
49-
}
50-
);
51-
if (response.ok) {
52-
return {
53-
status: response.status,
54-
};
55-
}
56-
return {
57-
error: (await response.json())["Error adding question: "],
58-
status: response.status,
59-
};
60-
} catch (err: any) {
61-
return { error: err.message, status: 0 };
62-
}
63-
}
64-
65-
export async function deleteQuestion(question: Question): Promise<StatusBody> {
66-
try {
67-
const response = await fetch(
68-
`${process.env.NEXT_PUBLIC_QUESTION_SERVICE}/questions/delete/${question.id}`,
69-
{
70-
method: "DELETE",
49+
body: JSON.stringify(validatedFields),
7150
headers: {
7251
"Content-type": "application/json; charset=UTF-8",
7352
},
7453
}
7554
);
76-
if (response.ok) {
77-
return {
78-
status: response.status,
79-
};
80-
}
81-
return {
82-
error: (await response.json())["Error deleting question: "],
83-
status: response.status,
84-
};
85-
} catch (err: any) {
86-
return { error: err.message, status: 0 };
87-
}
88-
}
89-
90-
export async function getAllQuestions(): Promise<Question[] | StatusBody> {
91-
try {
92-
const response = await fetch(
93-
`${process.env.NEXT_PUBLIC_QUESTION_SERVICE}/questions`
94-
);
95-
if (!response.ok) {
96-
return {
97-
error: await response.text(),
98-
status: response.status,
99-
};
100-
}
101-
return (await response.json()) as Question[];
102-
} catch (err: any) {
103-
return { error: err.message, status: 400 };
104-
}
105-
}
106-
107-
export async function getSessionLogin(
108-
validatedFields: {
109-
email: string;
110-
password: string;
111-
}
112-
): Promise<LoginResponse | StatusBody> {
113-
try {
114-
const res = await fetch(`${process.env.NEXT_PUBLIC_USER_SERVICE}/auth/login`, {
115-
method: "POST",
116-
body: JSON.stringify(validatedFields),
117-
headers: {
118-
"Content-type": "application/json; charset=UTF-8",
119-
}
120-
});
12155
const json = await res.json();
12256

12357
if (!res.ok) {
@@ -131,21 +65,19 @@ export async function getSessionLogin(
13165
}
13266
}
13367

134-
export async function postSignupUser(
135-
validatedFields: {
136-
username: string;
137-
email: string;
138-
password: string;
139-
}
140-
): Promise<SigninResponse | StatusBody> {
68+
export async function postSignupUser(validatedFields: {
69+
username: string;
70+
email: string;
71+
password: string;
72+
}): Promise<SigninResponse | StatusBody> {
14173
try {
14274
console.log(JSON.stringify(validatedFields));
14375
const res = await fetch(`${process.env.NEXT_PUBLIC_USER_SERVICE}/users`, {
14476
method: "POST",
14577
body: JSON.stringify(validatedFields),
14678
headers: {
14779
"Content-type": "application/json; charset=UTF-8",
148-
}
80+
},
14981
});
15082
const json = await res.json();
15183

peerprep/api/structs.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,6 @@ export const LoginFormSchema = z.object({
9595
.trim(),
9696
});
9797

98-
export function isError(
99-
obj: any | StatusBody
100-
): obj is StatusBody {
98+
export function isError(obj: any | StatusBody): obj is StatusBody {
10199
return (obj as StatusBody).status !== undefined;
102100
}

peerprep/app/actions/server_actions.ts

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,31 @@
1-
"use server"
2-
import { getSessionLogin, postSignupUser } from '@/api/gateway';
1+
"use server";
2+
import { getSessionLogin, postSignupUser } from "@/api/gateway";
33
// defines the server-sided login action.
4-
import { SignupFormSchema, LoginFormSchema, FormState, isError } from '@/api/structs';
5-
import { createSession } from '@/app/actions/session';
6-
import { redirect } from 'next/navigation';
4+
import {
5+
SignupFormSchema,
6+
LoginFormSchema,
7+
FormState,
8+
isError,
9+
} from "@/api/structs";
10+
import { createSession } from "@/app/actions/session";
11+
import { redirect } from "next/navigation";
712

813
// credit - taken from Next.JS Auth tutorial
914
export async function signup(state: FormState, formData: FormData) {
1015
// Validate form fields
1116
const validatedFields = SignupFormSchema.safeParse({
12-
username: formData.get('username'),
13-
email: formData.get('email'),
14-
password: formData.get('password'),
17+
username: formData.get("username"),
18+
email: formData.get("email"),
19+
password: formData.get("password"),
1520
});
16-
21+
1722
// If any form fields are invalid, return early
1823
if (!validatedFields.success) {
1924
return {
2025
errors: validatedFields.error.flatten().fieldErrors,
21-
}
26+
};
2227
}
23-
28+
2429
const json = await postSignupUser(validatedFields.data);
2530

2631
if (!isError(json)) {
@@ -35,17 +40,17 @@ export async function signup(state: FormState, formData: FormData) {
3540
export async function login(state: FormState, formData: FormData) {
3641
// Validate form fields
3742
const validatedFields = LoginFormSchema.safeParse({
38-
email: formData.get('email'),
39-
password: formData.get('password'),
43+
email: formData.get("email"),
44+
password: formData.get("password"),
4045
});
41-
46+
4247
// If any form fields are invalid, return early
4348
if (!validatedFields.success) {
4449
return {
4550
errors: validatedFields.error.flatten().fieldErrors,
46-
}
51+
};
4752
}
48-
53+
4954
const json = await getSessionLogin(validatedFields.data);
5055
if (!isError(json)) {
5156
await createSession(json.data.accessToken);

peerprep/app/actions/session.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
import 'server-only';
2-
import { cookies } from 'next/headers';
1+
import "server-only";
2+
import { cookies } from "next/headers";
33

44
export async function createSession(accessToken: string) {
55
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
6-
cookies().set('session', accessToken, {
6+
cookies().set("session", accessToken, {
77
httpOnly: true,
88
secure: true,
99
expires: expiresAt,
10-
sameSite: 'lax',
11-
path: '/',
12-
})
13-
}
10+
sameSite: "lax",
11+
path: "/",
12+
});
13+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { QuestionFullBody, StatusBody } from "@/api/structs";
2+
3+
export async function deleteQuestion(id: number): Promise<StatusBody> {
4+
const res = await fetch(
5+
`${process.env.NEXT_PUBLIC_NGINX}/api/internal/questions`,
6+
{
7+
method: "DELETE",
8+
body: JSON.stringify({ qid: id }),
9+
}
10+
);
11+
if (res.ok) {
12+
return { status: res.status };
13+
}
14+
const json = await res.json();
15+
return json as StatusBody;
16+
}
17+
18+
export async function addQuestion(
19+
question: QuestionFullBody
20+
): Promise<StatusBody> {
21+
const res = await fetch(
22+
`${process.env.NEXT_PUBLIC_NGINX}/api/internal/questions`,
23+
{
24+
method: "POST",
25+
body: JSON.stringify(question).replace(
26+
/(\"difficulty\":)\"([1-3])\"/,
27+
`$1$2`
28+
),
29+
}
30+
);
31+
if (res.ok) {
32+
return { status: res.status };
33+
}
34+
const json = await res.json();
35+
return json as StatusBody;
36+
}

0 commit comments

Comments
 (0)