Skip to content

Commit a246f34

Browse files
author
Nyasa
committed
handled api request in a separate file
1 parent d49c8f3 commit a246f34

File tree

4 files changed

+63
-28
lines changed

4 files changed

+63
-28
lines changed

app/schemas/api.tsx

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
export interface ApiResponse {
1+
export interface ApiResponse<T=unknown> {
2+
status: string;
23
message: string;
3-
data: unknown;
4+
data?: unknown;
5+
error?:string;
46
}

app/schemas/forms/login.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import * as z from "zod";
2+
3+
export const loginFormSchema = z.object({
4+
email: z
5+
.string()
6+
.email({
7+
message: "Invalid email address",
8+
})
9+
.trim(),
10+
password: z
11+
.string()
12+
.min(6, "Password must not be lesser than 6 characters")
13+
.max(20, "Password must not be greater than 20 characters")
14+
.trim(),
15+
});

app/services/login.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
1-
import { type loginFormSchema } from "@/schemas/forms/login";
1+
import { type loginFormSchema } from "../schemas/forms/login";
22
import { type z } from "zod";
33
import api from ".";
44
import { ApiResponse } from "../schemas/api";
55
import { handleAPIError } from "@/lib/error";
6+
interface LoginData {
7+
username: string;
8+
round: number;
9+
score: number;
10+
}
611

712
export async function login(body: z.infer<typeof loginFormSchema>) {
813
try {
9-
const { data } = await api.post<ApiResponse>(`login`, body);
10-
return data.message;
14+
const { data } = await api.post<ApiResponse<LoginData>>(`login`, body);
15+
return data;
1116
} catch (e) {
1217
throw handleAPIError(e);
1318
}

components/Login.tsx

Lines changed: 36 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ import React from "react";
44
import Image from "next/image";
55
import { useForm } from "react-hook-form";
66
import { zodResolver } from "@hookform/resolvers/zod";
7-
import * as z from "zod";
8-
import axios from "axios";
7+
import * as z from "zod";import { login } from "@/app/services/login";
98
import { useRouter } from "next/navigation";
109
import toast,{Toaster} from "react-hot-toast";
1110
import Button from "@/components/ui/Button";
@@ -18,6 +17,7 @@ import {
1817
FormMessage,
1918
} from "@/components/ui/form";
2019
import { Input } from "@/components/ui/input";
20+
import { ApiError } from "next/dist/server/api-utils";
2121

2222
// validation schema
2323
const formSchema = z.object({
@@ -37,40 +37,53 @@ export default function Login() {
3737
const router = useRouter();
3838
async function onSubmit(values: z.infer<typeof formSchema>) {
3939
try{
40-
const res = await axios.post("https://kabutar.codechefvit.com/login",
41-
{
42-
"email": values.email,
43-
"password": values.password
44-
}
45-
);
46-
if(res.status===200){
47-
const { status, message, data } = res.data;
40+
const res = await login(values);
41+
if(res.status==="success"){
42+
const { status, message, data } = res;
4843
toast.success("Login successful. Welcome, Chef!");
4944
router.push("/dashboard");
5045
}
5146
else{
52-
const { status, error }=res.data;
47+
const { status, error }=res;
5348
toast.error("An error occurred. Login failed.")
5449
console.error("Login failed:", error);
5550
}
5651
}
57-
catch(error:any){
58-
// console.log("Request failed with status code: ",error.response.status);
59-
// toast.error("An error occurred. Login failed.")
60-
// console.error("Login failed:", error);
61-
const status = error.response?.status;
62-
63-
if (status === 404) {
64-
// Email not found
52+
// catch(error:unknown){
53+
// // console.log("Request failed with status code: ",error.response.status);
54+
// // toast.error("An error occurred. Login failed.")
55+
// // console.error("Login failed:", error);
56+
// if (error instanceof ApiError) {
57+
// const statusCode = error.status;
58+
59+
// if (error.status === 404) {
60+
// // Email not found
61+
// form.setError("email", { type: "manual", message: "*Please enter valid email address" });
62+
// } else if (statusCode === 409) {
63+
// // Wrong password
64+
// form.setError("password", { type: "manual", message: "*Please enter correct password" });
65+
// } else {
66+
// // Other errors
67+
// toast.error(error.response?.data?.message || "An error occurred");}
68+
// }
69+
// else {
70+
// // Not an axios error
71+
// toast.error("Unexpected error occurred");
72+
// console.error(error);
73+
// }
74+
// }
75+
catch (error: unknown) {
76+
const err = error as { status?: number; message: string };
77+
78+
if (err.message === "User not found") {
6579
form.setError("email", { type: "manual", message: "*Please enter valid email address" });
66-
} else if (status === 409) {
67-
// Wrong password
80+
} else if (err.message === "Invalid password") {
6881
form.setError("password", { type: "manual", message: "*Please enter correct password" });
6982
} else {
70-
// Other errors
71-
toast.error(error.response?.data?.message || "An error occurred");}
83+
toast.error(err.message || "An error occurred");
7284
}
7385
}
86+
}
7487

7588
return (
7689
<div className="relative flex h-screen w-full items-center justify-center text-white overflow-hidden">

0 commit comments

Comments
 (0)