diff --git a/src/api/_shared/config.ts b/src/api/_shared/config.ts new file mode 100644 index 0000000..65d1acb --- /dev/null +++ b/src/api/_shared/config.ts @@ -0,0 +1,25 @@ +/** + * API ベースパスをくっつける関数 + */ +export const withAPIBasePath = (path: string) => { + const basePath = process.env.NEXT_PUBLIC_API_BASE_PATH; + + if (!basePath) { + throw new Error("API ベースパスが未設定です"); + } + + return `${basePath}${path}`; +}; + +/** + * API キーをくっつける関数 + */ +export const withAPIKeyHeader = (headers: Record) => { + const apiKey = process.env.NEXT_PUBLIC_API_KEY; + + if (!apiKey) { + throw new Error("API キーが未設定です"); + } + + return { ...headers, "X-Api-Key": apiKey }; +}; diff --git a/src/api/fav/arts/fetchArtFav.ts b/src/api/fav/arts/fetchArtFav.ts new file mode 100644 index 0000000..3aeadfb --- /dev/null +++ b/src/api/fav/arts/fetchArtFav.ts @@ -0,0 +1,18 @@ +import { withAPIBasePath, withAPIKeyHeader } from "@/api/_shared/config"; + +type FetchArtFavRequestParams = { + id: string; +}; + +type FetchArtFavResponseBody = { + fav: number; +}; + +export const fetchArtFav = async (params: FetchArtFavRequestParams) => { + const res = await fetch(withAPIBasePath(`/fav/arts/${params.id}`), { + method: "get", + headers: withAPIKeyHeader({}), + }); + + return await (res.json() as Promise); +}; diff --git a/src/api/fav/arts/incrementArtFav.ts b/src/api/fav/arts/incrementArtFav.ts new file mode 100644 index 0000000..315107d --- /dev/null +++ b/src/api/fav/arts/incrementArtFav.ts @@ -0,0 +1,18 @@ +import { withAPIBasePath, withAPIKeyHeader } from "@/api/_shared/config"; + +type IncrementArtFavRequestParams = { + id: string; +}; + +type IncrementArtFavResponseBody = { + fav: number; +}; + +export const incrementArtFav = async (params: IncrementArtFavRequestParams) => { + const res = await fetch(withAPIBasePath(`/fav/arts/${params.id}`), { + method: "post", + headers: withAPIKeyHeader({}), + }); + + return await (res.json() as Promise); +}; diff --git a/src/api/fav/arts/syncArtsFav.ts b/src/api/fav/arts/syncArtsFav.ts new file mode 100644 index 0000000..4fafbdf --- /dev/null +++ b/src/api/fav/arts/syncArtsFav.ts @@ -0,0 +1,18 @@ +import { withAPIBasePath, withAPIKeyHeader } from "@/api/_shared/config"; + +type SyncArtsFavRequestParams = { + id: string; +}; + +type SyncArtsFavResponseBody = { + fav: number; +}; + +export const syncArtsFav = async (params: SyncArtsFavRequestParams) => { + const res = await fetch(withAPIBasePath(`/fav/arts/${params.id}`), { + method: "post", + headers: withAPIKeyHeader({}), + }); + + return await (res.json() as Promise); +}; diff --git a/src/api/index.ts b/src/api/index.ts new file mode 100644 index 0000000..37559ec --- /dev/null +++ b/src/api/index.ts @@ -0,0 +1,9 @@ +import { fetchArtFav } from "./fav/arts/fetchArtFav"; +import { incrementArtFav } from "./fav/arts/incrementArtFav"; +import { syncArtsFav } from "./fav/arts/syncArtsFav"; + +export const api = { + fetchArtFav, + incrementArtFav, + syncArtsFav, +};