Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace Fetch -> Ky #73

Merged
merged 4 commits into from
Oct 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ export const { handlers, auth, signIn, signOut, unstable_update } = NextAuth({
refreshToken,
accessToken,
};
return token;
}
}

Expand Down
5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,14 @@
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"dayjs": "^1.11.12",
"es-toolkit": "^1.24.0",
"framer-motion": "^11.3.24",
"html-react-parser": "^5.1.16",
"jose": "^5.7.0",
"lodash": "^4.17.21",
"ky": "^1.7.2",
"next": "14.2.4",
"next-auth": "5.0.0-beta.20",
"nuqs": "^1.17.8",
"path-to-regexp": "^7.1.0",
"react": "^18",
"react-daum-postcode": "^3.1.3",
"react-dom": "^18",
Expand Down Expand Up @@ -71,7 +71,6 @@
"@tanstack/eslint-plugin-query": "^5.50.1",
"@types/canvas-confetti": "^1.6.4",
"@types/kakao-js-sdk": "^1.39.5",
"@types/lodash": "^4.17.7",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
Expand Down
32 changes: 17 additions & 15 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

66 changes: 66 additions & 0 deletions src/apis/FiestaInstance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import type { KyRequest, NormalizedOptions } from "ky";
import ky from "ky";

import { env } from "@/env";
import { getClientSideSession } from "@/lib/session";

import { getServerSideSession } from "./auth/auth";
import { FiestaResponse } from "./instance";

const addAuthTokenToHeader = async (
_request: KyRequest,
_options: NormalizedOptions,
) => {
const isServer = typeof window === "undefined";

const session = isServer
? await getServerSideSession()
: await getClientSideSession();

if (session) {
_request.headers.set("Authorization", `Bearer ${session.accessToken}`);
}

return _request;
};

const createKyInstance = () => {
return ky.create({
prefixUrl: env.NEXT_PUBLIC_BASE_URL,
hooks: {
beforeRequest: [addAuthTokenToHeader],
},
retry: {
limit: 2,
methods: ["get", "post", "put", "patch", "delete"],
statusCodes: [408, 413, 429, 500, 502, 503, 504],
},
});
};

const Instance = createKyInstance();

const FiestaInstance = {
get: <T>(url: string, options?: RequestInit) =>
Instance.get(url, options)
.json<FiestaResponse<T>>()
.then((res) => res.data),
post: <T>(url: string, json?: unknown, options?: RequestInit) =>
Instance.post(url, { json, ...options })
.json<FiestaResponse<T>>()
.then((res) => res.data),
put: <T>(url: string, json?: unknown, options?: RequestInit) =>
Instance.put(url, { json, ...options })
.json<FiestaResponse<T>>()
.then((res) => res.data),
patch: <T>(url: string, json?: unknown, options?: RequestInit) =>
Instance.patch(url, { json, ...options })
.json<FiestaResponse<T>>()
.then((res) => res.data),
delete: <T>(url: string, options?: RequestInit) =>
Instance.delete(url, options)
.json<FiestaResponse<T>>()
.then((res) => res.data),
};

export default FiestaInstance;
11 changes: 7 additions & 4 deletions src/apis/auth/auth.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
"use server";

import instance from "@/apis/instance";
import { auth, signIn, signOut } from "@/auth";
import FIESTA_ENDPOINTS from "@/config/apiEndpoints";

import { env } from "@/env";
import FiestaInstance from "../FiestaInstance";
import {
RefreshTokenResponse,
SocialLoginRequest,
SocialLoginResponse,
} from "./authType";
import { env } from "@/env";

const ENDPOINT = FIESTA_ENDPOINTS.users;

export async function postOauthLogin(body: SocialLoginRequest) {
const endpoint = ENDPOINT.login;
const { data } = await instance.post<SocialLoginResponse>(endpoint, body);
const response = await FiestaInstance.post<SocialLoginResponse>(
endpoint,
body,
);

return data;
return response;
}

export const postSignOut = async () => {
Expand Down
6 changes: 3 additions & 3 deletions src/apis/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export class ReviewError extends FiestaError {
}
}

function isFiestaError(error: unknown): error is FiestaError {
export function isFiestaError(error: unknown): error is FiestaError {
return (
typeof error === "object" &&
error !== null &&
Expand All @@ -61,7 +61,7 @@ function isFiestaError(error: unknown): error is FiestaError {

export function createFiestaError(error: unknown) {
if (!isFiestaError(error)) {
return new Error(`Unknown Error: ${JSON.stringify(error)}`);
return new LogsError(500, "C000", "UnknownError");
}

const { code, message, statusCode } = error;
Expand All @@ -86,5 +86,5 @@ export function createFiestaError(error: unknown) {
return new ReviewError(statusCode, code, message);
}

return new Error(`Something went wrong: ${JSON.stringify(error)}`);
return new LogsError(500, "C000", "UnknownError");
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use server";

import { ClientError } from "@/apis/error";
import instance from "@/apis/instance";
import FiestaInstance from "@/apis/FiestaInstance";
import FIESTA_ENDPOINTS from "@/config/apiEndpoints";

import { DetailFestivalResponse } from "../detailFestival/detailFestivalType";
Expand All @@ -11,13 +11,13 @@ const ENDPOINT = FIESTA_ENDPOINTS.festivals;
export async function getFestivalBookmark(festivalId: number) {
const endpoint = ENDPOINT.detail(String(festivalId));
try {
const response = await instance.get<
const response = await FiestaInstance.get<
Pick<DetailFestivalResponse, "bookmarkCount" | "isBookmarked">
>(endpoint, {
cache: "no-store",
});

const { isBookmarked, bookmarkCount } = response.data;
const { isBookmarked, bookmarkCount } = response;

return {
isBookmarked,
Expand Down
12 changes: 7 additions & 5 deletions src/apis/festivals/bookmarkFestival/bookmarkFestival.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,28 @@
"use server";

import debounce from "lodash/debounce";
import { debounce } from "es-toolkit/function";

import { ClientError } from "@/apis/error";
import instance from "@/apis/instance";
import FiestaInstance from "@/apis/FiestaInstance";
import FIESTA_ENDPOINTS from "@/config/apiEndpoints";

import { bookmarkFestivalResponse } from "./bookmarkFestivalType";

const ENDPOINT = FIESTA_ENDPOINTS.festivals;

export const debouncedPatchBookmarkFestival = debounce(
(endpoint: string) => instance.patch<bookmarkFestivalResponse>(endpoint),
(endpoint: string) =>
FiestaInstance.patch<bookmarkFestivalResponse>(endpoint),
400,
);

export async function patchBookmarkFestival(festivalId: number) {
const endpoint = ENDPOINT.bookmark(festivalId);
try {
const response = await instance.patch<bookmarkFestivalResponse>(endpoint);
const response =
await FiestaInstance.patch<bookmarkFestivalResponse>(endpoint);

return response.data;
return response;
} catch (error) {
if (error instanceof ClientError) {
throw new Error("Session required");
Expand Down
11 changes: 5 additions & 6 deletions src/apis/festivals/createFestival/createFestival.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import instance from "@/apis/instance";
import FiestaInstance from "@/apis/FiestaInstance";
import FIESTA_ENDPOINTS from "@/config/apiEndpoints";
import { CreateFestivalType } from "@/validations/CreateFestivalSchema";

Expand All @@ -19,10 +19,9 @@ export async function createFestival(payload: CreateFestivalType) {
formData.append("images", image);
});

const { data } = await instance.post<CreateFestivalResponse>(
ENDPOINT,
formData,
);
const response = await FiestaInstance.post<CreateFestivalResponse>(ENDPOINT, {
body: formData,
});

return data;
return response;
}
25 changes: 8 additions & 17 deletions src/apis/festivals/detailFestival/detailFestival.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"use server";

import { ClientError } from "@/apis/error";
import instance from "@/apis/instance";
import FiestaInstance from "@/apis/FiestaInstance";
import FIESTA_ENDPOINTS from "@/config/apiEndpoints";

import { DetailFestivalResponse } from "./detailFestivalType";
Expand All @@ -10,20 +9,12 @@ const ENDPOINT = FIESTA_ENDPOINTS.festivals;

export async function getDetailFestival(festivalId: string) {
const endpoint = ENDPOINT.detail(festivalId);
try {
const response = await instance.get<DetailFestivalResponse>(endpoint, {
// cache: "no-store",
next: {
revalidate: 86400,
tags: [`festivals/${festivalId}`],
},
});
const response = await FiestaInstance.get<DetailFestivalResponse>(endpoint, {
next: {
revalidate: 86400,
tags: [`festivals/${festivalId}`],
},
});

return response.data;
} catch (error) {
if (error instanceof ClientError) {
throw new Error("Session required");
}
throw new Error("something went wrong");
}
return response;
}
Loading