Skip to content

feat: backend API에 대한 환경 및 context 변수들 추가 #9

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

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
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
6 changes: 5 additions & 1 deletion apps/pyconkr/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@ import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import MainLayout from "./components/layout";
import { Test } from "./components/pages/test";
import { IS_DEBUG_ENV } from "./consts/index.ts";

import * as Common from "@frontend/common";

export const App: React.FC = () => {
return (
<BrowserRouter>
<Routes>
<Route element={<MainLayout />}>
<Route path="/" element={<Test />} />
{ IS_DEBUG_ENV && <Route path="/debug" element={<Test />} /> }
<Route path="*" element={<Common.Components.DynamicRoutePage />} />
</Route>
</Routes>
</BrowserRouter>
Expand Down
2 changes: 1 addition & 1 deletion apps/pyconkr/src/components/layout/Footer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export default function Footer({
],
icons = defaultIcons,
}: FooterProps) {
const { sendEmail } = Common.Hooks.useEmail();
const { sendEmail } = Common.Hooks.Common.useEmail();

return (
<FooterContainer>
Expand Down
5 changes: 5 additions & 0 deletions apps/pyconkr/src/components/layout/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ const LayoutContainer = styled.div`

const MainContent = styled.main`
flex: 1;

display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
`;

export default function MainLayout() {
Expand Down
7 changes: 6 additions & 1 deletion apps/pyconkr/src/components/pages/test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import * as React from "react";

import { Box, Button } from "@mui/material";

import { BackendTestPage } from '../../debug/page/backend_test';
import { MdiTestPage } from "../../debug/page/mdi_test";
import { ShopTestPage } from "../../debug/page/shop_test";

type SelectedTabType = "shop" | "mdi";
type SelectedTabType = "shop" | "mdi" | "backend";

export const Test: React.FC = () => {
const [selectedTab, setSelectedTab] = React.useState<SelectedTabType>("mdi");
Expand All @@ -18,8 +19,12 @@ export const Test: React.FC = () => {
<Button variant="contained" onClick={() => setSelectedTab("mdi")}>
MDI Test
</Button>
<Button variant="contained" onClick={() => setSelectedTab("backend")}>
Backend Test
</Button>
{selectedTab === "shop" && <ShopTestPage />}
{selectedTab === "mdi" && <MdiTestPage />}
{selectedTab === "backend" && <BackendTestPage />}
</Box>
);
};
1 change: 1 addition & 0 deletions apps/pyconkr/src/consts/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const IS_DEBUG_ENV = import.meta.env.MODE === "development"
44 changes: 44 additions & 0 deletions apps/pyconkr/src/debug/page/backend_test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import * as React from "react";
import * as R from "remeda";

import { Button, CircularProgress, MenuItem, Select, Stack } from '@mui/material';
import { ErrorBoundary, Suspense } from '@suspensive/react';

import * as Common from "@frontend/common";

const SiteMapRenderer: React.FC = () => {
const { data } = Common.Hooks.BackendAPI.useFlattenSiteMapQuery();
return <pre style={{ whiteSpace: "pre-wrap" }}>{JSON.stringify(Common.Utils.buildNestedSiteMap(data), null, 2)}</pre>
};

const PageIdSelector: React.FC<{ inputRef: React.Ref<HTMLSelectElement> }> = ({ inputRef }) => {
const { data } = Common.Hooks.BackendAPI.useFlattenSiteMapQuery();

return <Select inputRef={inputRef}>
{data.map((siteMap) => <MenuItem key={siteMap.id} value={siteMap.page}>{siteMap.name}</MenuItem>)}
</Select>
}

const SuspenseWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => (
<ErrorBoundary fallback={Common.Components.ErrorFallback}>
<Suspense fallback={<CircularProgress />}>
{children}
</Suspense>
</ErrorBoundary>
)

export const BackendTestPage: React.FC = () => {
const inputRef = React.useRef<HTMLSelectElement>(null);
const [pageId, setPageId] = React.useState<string | null>(null);

return <Stack>
<br />
<SuspenseWrapper><SiteMapRenderer /></SuspenseWrapper>
<br />
<SuspenseWrapper><PageIdSelector inputRef={inputRef} /></SuspenseWrapper>
<br />
<Button variant="outlined" onClick={() => setPageId(inputRef.current?.value ?? null)}>페이지 렌더링</Button>
<br />
{R.isString(pageId) ? <SuspenseWrapper><Common.Components.PageRenderer id={pageId} /></SuspenseWrapper> : <>페이지를 선택해주세요.</>}
</Stack>
}
5 changes: 4 additions & 1 deletion apps/pyconkr/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import * as Common from "@frontend/common";
import * as Shop from "@frontend/shop";

import { App } from "./App.tsx";
import { IS_DEBUG_ENV } from './consts/index.ts';
import { globalStyles, muiTheme } from "./styles/globalStyles.ts";

const queryClient = new QueryClient({
Expand All @@ -35,8 +36,10 @@ const queryClient = new QueryClient({
});

const CommonOptions: Common.Contexts.ContextOptions = {
debug: import.meta.env.MODE === "development",
debug: IS_DEBUG_ENV,
baseUrl: '.',
backendApiDomain: import.meta.env.VITE_PYCONKR_BACKEND_API_DOMAIN,
backendApiTimeout: 10000,
};

const ShopOptions: Shop.Contexts.ContextOptions = {
Expand Down
1 change: 1 addition & 0 deletions apps/pyconkr/vite-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ interface ViteTypeOptions {
}

interface ImportMetaEnv {
readonly VITE_PYCONKR_BACKEND_API_DOMAIN: string;
readonly VITE_PYCONKR_SHOP_API_DOMAIN: string;
readonly VITE_PYCONKR_SHOP_CSRF_COOKIE_NAME: string;
readonly VITE_PYCONKR_SHOP_IMP_ACCOUNT_ID: string;
Expand Down
1 change: 1 addition & 0 deletions dotenv/.env.development
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
VITE_PYCONKR_BACKEND_API_DOMAIN=https://rest-api.dev.pycon.kr
VITE_PYCONKR_SHOP_API_DOMAIN=https://shop-api.dev.pycon.kr
VITE_PYCONKR_SHOP_CSRF_COOKIE_NAME=DEBUG_csrftoken
VITE_PYCONKR_SHOP_IMP_ACCOUNT_ID=imp80859147
1 change: 1 addition & 0 deletions dotenv/.env.production
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
VITE_PYCONKR_BACKEND_API_DOMAIN=https://rest-api.pycon.kr
VITE_PYCONKR_SHOP_API_DOMAIN=https://shop-api.pycon.kr
VITE_PYCONKR_SHOP_CSRF_COOKIE_NAME=csrftoken
VITE_PYCONKR_SHOP_IMP_ACCOUNT_ID=imp96676915
176 changes: 176 additions & 0 deletions packages/common/src/apis/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import * as R from "remeda";

import CommonSchemas from "../schemas";

const DEFAULT_ERROR_MESSAGE = "알 수 없는 문제가 발생했습니다, 잠시 후 다시 시도해주세요.";
const DEFAULT_ERROR_RESPONSE = {
type: "unknown",
errors: [{ code: "unknown", detail: DEFAULT_ERROR_MESSAGE, attr: null }],
};

export class BackendAPIClientError extends Error {
readonly name = "BackendAPIClientError";
readonly status: number;
readonly detail: CommonSchemas.ErrorResponseSchema;
readonly originalError: unknown;

constructor(error?: unknown) {
let message: string = DEFAULT_ERROR_MESSAGE;
let detail: CommonSchemas.ErrorResponseSchema = DEFAULT_ERROR_RESPONSE;
let status = -1;

if (axios.isAxiosError(error)) {
const response = error.response;

if (response) {
status = response.status;
detail = CommonSchemas.isObjectErrorResponseSchema(response.data)
? response.data
: {
type: "axios_error",
errors: [
{
code: "unknown",
detail: R.isString(response.data)
? response.data
: DEFAULT_ERROR_MESSAGE,
attr: null,
},
],
};
}
} else if (error instanceof Error) {
message = error.message;
detail = {
type: error.name || typeof error || "unknown",
errors: [{ code: "unknown", detail: error.message, attr: null }],
};
}

super(message);
this.originalError = error || null;
this.status = status;
this.detail = detail;
}

isRequiredAuth(): boolean {
return this.status === 401 || this.status === 403;
}
}

type AxiosRequestWithoutPayload = <T = any, R = AxiosResponse<T>, D = any>(
url: string,
config?: AxiosRequestConfig<D>
) => Promise<R>;
type AxiosRequestWithPayload = <T = any, R = AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: AxiosRequestConfig<D>
) => Promise<R>;

export class BackendAPIClient {
readonly baseURL: string;
private readonly backendAPI: AxiosInstance;

constructor(baseURL: string, timeout: number) {
const headers = { "Content-Type": "application/json" };
this.baseURL = baseURL;
this.backendAPI = axios.create({ baseURL, timeout, headers });
}

_safe_request_without_payload(
requestFunc: AxiosRequestWithoutPayload
): AxiosRequestWithoutPayload {
return async <T = any, R = AxiosResponse<T>, D = any>(
url: string,
config?: AxiosRequestConfig<D>
) => {
try {
return await requestFunc<T, R, D>(url, config);
} catch (error) {
throw new BackendAPIClientError(error);
}
};
}

_safe_request_with_payload(
requestFunc: AxiosRequestWithPayload
): AxiosRequestWithPayload {
return async <T = any, R = AxiosResponse<T>, D = any>(
url: string,
data: D,
config?: AxiosRequestConfig<D>
) => {
try {
return await requestFunc<T, R, D>(url, data, config);
} catch (error) {
throw new BackendAPIClientError(error);
}
};
}

async get<T, D = any>(
url: string,
config?: AxiosRequestConfig<D>
): Promise<T> {
return (
await this._safe_request_without_payload(this.backendAPI.get)<
T,
AxiosResponse<T>,
D
>(url, config)
).data;
}
async post<T, D>(
url: string,
data: D,
config?: AxiosRequestConfig<D>
): Promise<T> {
return (
await this._safe_request_with_payload(this.backendAPI.post)<
T,
AxiosResponse<T>,
D
>(url, data, config)
).data;
}
async put<T, D>(
url: string,
data: D,
config?: AxiosRequestConfig<D>
): Promise<T> {
return (
await this._safe_request_with_payload(this.backendAPI.put)<
T,
AxiosResponse<T>,
D
>(url, data, config)
).data;
}
async patch<T, D>(
url: string,
data: D,
config?: AxiosRequestConfig<D>
): Promise<T> {
return (
await this._safe_request_with_payload(this.backendAPI.patch)<
T,
AxiosResponse<T>,
D
>(url, data, config)
).data;
}
async delete<T, D = any>(
url: string,
config?: AxiosRequestConfig<D>
): Promise<T> {
return (
await this._safe_request_without_payload(this.backendAPI.delete)<
T,
AxiosResponse<T>,
D
>(url, config)
).data;
}
}
9 changes: 9 additions & 0 deletions packages/common/src/apis/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import CommonSchemas from "../schemas";
import { BackendAPIClient } from "./client";

namespace BackendAPIs {
export const listSiteMaps = (client: BackendAPIClient) => () => client.get<CommonSchemas.FlattenedSiteMapSchema[]>("v1/cms/sitemap/");
export const retrievePage = (client: BackendAPIClient) => (id: string) => client.get<CommonSchemas.PageSchema>(`v1/cms/page/${id}/`);
}

export default BackendAPIs;
Loading