Skip to content

Commit 99542a9

Browse files
api.tsx
1 parent 98dc67b commit 99542a9

File tree

5 files changed

+61
-1
lines changed

5 files changed

+61
-1
lines changed

app/services/login.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { type loginFormSchema } from "@/schemas/forms/login";
2+
import { type z } from "zod";
3+
import api from ".";
4+
import { ApiResponse } from "../schemas/api";
5+
import { handleAPIError } from "@/lib/error";
6+
7+
export async function login(body: z.infer<typeof loginFormSchema>) {
8+
try {
9+
const { data } = await api.post<ApiResponse>(`login`, body);
10+
return data.message;
11+
} catch (e) {
12+
throw handleAPIError(e);
13+
}
14+
}
15+
16+
17+

lib/error.tsx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
2+
import axios, { type AxiosError } from "axios";
3+
import { ApiError } from "next/dist/server/api-utils";
4+
import { toSentenceCase } from "@/lib/utils";
5+
6+
export function handleAPIError(err: unknown): ApiError {
7+
if (axios.isAxiosError(err)) {
8+
const error = err as AxiosError;
9+
const response = error.response;
10+
const data = response?.data;
11+
if (data) {
12+
const msg = (data as { error: string })?.error;
13+
if (msg) {
14+
return new ApiError(response.status, toSentenceCase(msg));
15+
}
16+
}
17+
}
18+
return new ApiError(500, "Something went wrong");
19+
}

lib/utils.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,18 @@ import { twMerge } from "tailwind-merge"
44
export function cn(...inputs: ClassValue[]) {
55
return twMerge(clsx(inputs))
66
}
7+
8+
export function toSentenceCase(input: string): string {
9+
const trimmedInput = input.trim();
10+
if (trimmedInput.length === 0) {
11+
return "";
12+
}
13+
14+
const sentences = trimmedInput.split(/(?<=[.!?])\s+/);
15+
16+
const sentenceCased = sentences.map((sentence) => {
17+
return sentence.charAt(0).toUpperCase() + sentence.slice(1);
18+
});
19+
20+
return sentenceCased.join(" ");
21+
}

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@
3232
"react-hot-toast": "^2.6.0",
3333
"react-icons": "^5.5.0",
3434
"react-markdown": "^10.1.0",
35-
"tailwind-merge": "^3.3.1"
35+
"tailwind-merge": "^3.3.1",
36+
"zod": "^4.1.9"
3637
},
3738
"devDependencies": {
3839
"@eslint/eslintrc": "^3",

pnpm-lock.yaml

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)