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

tswagger 연동 및 react-query 예시코드 작성 #66

Open
wants to merge 8 commits into
base: develop
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
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_API_URL=http://43.200.247.241:8080
3 changes: 3 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
tailwind.config.js
node_modules
src/apis/apiGenerator
dist
4 changes: 4 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
tailwind.config.js
node_modules
src/apis/apiGenerator
dist
15 changes: 10 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# Life 4 Cut FE

## 사이트 URL: https://life-4-cut.netlify.app/
### 사이트 URL: https://life-4-cut.netlify.app/

## Run & Build
### Run & Build

| description | command | port |
| --------------------- | -------------- | ---- |
| 개발모드 실행 | `yarn dev` | 5173 |
| --------------------- | -------------- |------|
| 개발모드 실행 | `yarn dev` | 8080 |
| 프로덕션 빌드 preview | `yarn preview` | 4173 |
| 빌드 | `yarn build` | |

Expand All @@ -19,7 +19,12 @@
| 스토리북 실행 | `yarn storybook` | 6006 |
| 스토리북 빌드 | `yarn build-storybook` | |

## 디렉토리 구조
### tswagger
api fetch를 위한 코드를 백엔드 swagger API 문서 기반으로 생성합니다.
```bash
yarn tswagger
```
### 디렉토리 구조

```text
📦src
Expand Down
12 changes: 10 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,20 @@
"build-storybook": "storybook build",
"commit": "cz",
"chromatic": "chromatic --exit-zero-on-changes",
"test-storybook": "test-storybook"
"test-storybook": "test-storybook",
"tswagger": "npx tswagger"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@hookform/resolvers": "^3.3.1",
"axios": "^1.6.2",
"pretendard": "^1.3.8",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.45.4",
"react-query": "^3.39.3",
"react-router-dom": "^6.14.2",
"vercel": "^31.4.0",
"yup": "^1.2.0"
Expand Down Expand Up @@ -75,14 +78,19 @@
"vite-tsconfig-paths": "^4.2.0"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"src/!(apis/apiGenerator)/**/*.{js,jsx,ts,tsx}": [
"prettier --write",
"eslint --cache --fix"
]
},
"resolutions": {
"jackspeak": "2.1.1"
},
"tswagger": {
"src": "http://43.200.247.241:8080/docs/openapi3.json",
"pluginsDir": "src/apis",
"pluginName": "apiGenerator"
},
"config": {
"commitizen": {
"path": "cz-conventional-changelog"
Expand Down
33 changes: 28 additions & 5 deletions src/Main.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { QueryCache, QueryClient, QueryClientProvider } from 'react-query';
import { BrowserRouter } from 'react-router-dom';

import { ModalProvider } from '@/contexts/ModalProvider';
Expand All @@ -9,10 +10,32 @@ import './global.css';

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<BrowserRouter>
<ModalProvider>
<App />
</ModalProvider>
</BrowserRouter>
<QueryClientProvider
client={
new QueryClient({
defaultOptions: {
queries: {
retry: false,
refetchOnWindowFocus: false,
cacheTime: 0,
},
mutations: {
retry: false,
},
},
queryCache: new QueryCache({
onError: (error: any) => {
alert(error?.response?.data.message);
},
}),
})
}
>
<BrowserRouter>
<ModalProvider>
<App />
</ModalProvider>
</BrowserRouter>
</QueryClientProvider>
</React.StrictMode>
);
112 changes: 112 additions & 0 deletions src/apis/apiGenerator/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/* eslint-disable */
// noinspection ES6UnusedImports,JSUnusedLocalSymbols

import Axios, { AxiosStatic, AxiosRequestConfig, AxiosResponse } from 'axios'
import { CreatePictureResponse, EmptyResponse, GetMyRoleInAlbumResponse, GetPictureInSlotResponse, SearchTagResponse, UserDuplicateResponse, UserFindResponse } from './types'
import { integer, long, float, double, byte, binary, date, dateTime, password } from './types'
export interface $customExtendResponse {}
type $R<T> = Promise<T> & { readonly response: Promise<AxiosResponse<T> & $customExtendResponse> }
export const $axiosConfig: Required<Parameters<AxiosStatic['create']>>[0] = {}
const $ep = (_: any) => ({
api: {
v1: {
albums: {
/** @param albumId 앨범 아이디 */
albumId: (albumId: number) => ({
pictures: {
/**
* 앨범내 페이지별 사진 목록을 조회한다
*
* @returns 200
* @summary 앨범내 페이지별 사진 목록을 조회한다
*/
get: <$T = GetPictureInSlotResponse>($config?: AxiosRequestConfig): $R<$T> => _('get', `/api/v1/albums/${albumId}/pictures`, $config),
/**
* 사진을 업로드한다
*
* @returns 200
* @summary 사진을 업로드한다
*/
post: <$T = CreatePictureResponse>($config?: AxiosRequestConfig): $R<$T> => _('post', `/api/v1/albums/${albumId}/pictures`, undefined, $config),
/** @param pictureId 사진 아이디 */
pictureId: (pictureId: number) => ({
/**
* 사진을 수정한다
*
* @returns 200
* @summary 사진을 수정한다
*/
patch: <$T = EmptyResponse>($config?: AxiosRequestConfig): $R<$T> => _('patch', `/api/v1/albums/${albumId}/pictures/${pictureId}`, undefined, $config)
})
},
roles: {
me: {
/**
* 앨범에 대한 내 권한을 조회한다
*
* @returns 200
* @summary 앨범에 대한 내 권한을 조회한다
*/
get: <$T = GetMyRoleInAlbumResponse>($config?: AxiosRequestConfig): $R<$T> => _('get', `/api/v1/albums/${albumId}/roles/me`, $config)
}
},
tags: {
/**
* 태그를 검색한다
*
* @param keyword 검색어
* @returns 200
* @summary 태그를 검색한다
*/
get: <$T = SearchTagResponse>(keyword?: string, $config?: AxiosRequestConfig): $R<$T> => _('get', `/api/v1/albums/${albumId}/tags`, { params: { keyword }, ...$config })
}
})
},
users: {
/**
* 닉네임 유저 조회 API
*
* 404: 404
*
* @param nickname 유저 닉네임
* @returns 200
* @summary 닉네임 유저 조회 API
*/
get: <$T = UserFindResponse>(nickname: string, $config?: AxiosRequestConfig): $R<$T> => _('get', `/api/v1/users`, { params: { nickname }, ...$config }),
duplicate: {
/**
* 닉네임으로 유저 조회 API
*
* @param nickname 유저 닉네임
* @returns 200
* @summary 닉네임으로 유저 조회 API
*/
get: <$T = UserDuplicateResponse>(nickname: string, $config?: AxiosRequestConfig): $R<$T> => _('get', `/api/v1/users/duplicate`, { params: { nickname }, ...$config })
},
me: {
/**
* 마이페이지 정보 조회 API
*
* @returns 200
* @summary 마이페이지 정보 조회 API
*/
get: <$T = UserFindResponse>($config?: AxiosRequestConfig): $R<$T> => _('get', `/api/v1/users/me`, $config),
/**
* 유저정보 수정 API
*
* 204: 204
*
* @returns undefined
* @summary 유저정보를 수정한다.
*/
patch: <$T = any>($config?: AxiosRequestConfig): $R<$T> => _('patch', `/api/v1/users/me`, undefined, $config)
}
}
}
}
})
export const apiGenerator = ($axios = Axios.create($axiosConfig)) => $ep((method: string, ...args: any) => {
const promise = ($axios as any)[method](...args)
return Object.defineProperty(promise.then((x: any) => x.data), 'response', {value: promise})
})

56 changes: 56 additions & 0 deletions src/apis/apiGenerator/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/* eslint-disable */
// noinspection ES6UnusedImports,JSUnusedLocalSymbols

/** CreatePictureResponse */
export type CreatePictureResponse = {
data?: { id?: number }
/** 응답 메시지 */
message?: string
}
/** EmptyResponse */
export type EmptyResponse = {
/** 데이터 */
data?: any
/** 응답 메시지 */
message?: string
}
/** GetMyRoleInAlbumResponse */
export type GetMyRoleInAlbumResponse = {
data?: { role?: string }
/** 응답 메시지 */
message?: string
}
/** GetPictureInSlotResponse */
export type GetPictureInSlotResponse = {
data?: { pictures?: Array<{ layout?: string, path?: string, pictureId?: number, location?: string, tagNames?: Array<any | boolean | string | number>, picturedAt?: string, content?: string }> }
/** 응답 메시지 */
message?: string
}
/** SearchTagResponse */
export type SearchTagResponse = {
data?: { tags?: Array<{ name?: string, id?: number }> }
/** 응답 메시지 */
message?: string
}
/** UserDuplicateResponse */
export type UserDuplicateResponse = {
data?: { isDuplicated?: boolean }
/** 응답 메시지 */
message?: string
}
/** UserFindResponse */
export type UserFindResponse = {
/** 데이터 */
data?: { nickname?: string, profilePath?: string, userId?: number, email?: string }
/** 응답 메시지 */
message?: string
}
export type integer = number
export type long = number
export type float = number
export type double = number
export type byte = string
export type binary = string
export type date = string
export type dateTime = string
export type password = string
12 changes: 12 additions & 0 deletions src/apis/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import axios from 'axios';

import { apiGenerator } from '@/apis/apiGenerator';

const BASE_URL = import.meta.env.PROD ? import.meta.env.VITE_API_URL : '/api';

const instance = axios.create({
baseURL: BASE_URL,
timeout: 30000,
});

export const api = apiGenerator(instance).api.v1;
21 changes: 21 additions & 0 deletions src/apis/queries/useUserNicknameQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useQuery } from 'react-query';

import { api } from '@/apis';

interface useUserNicknameQueryParams {
nickname: string;
}
export function useUserNicknameQuery({ nickname }: useUserNicknameQueryParams) {
const { data } = useQuery(
['userNicknameInfo'],
async () => {
const { data } = await api.users.get(nickname);
return data;
},
{
enabled: !!nickname,
}
);

return { data };
}
3 changes: 3 additions & 0 deletions src/domain/login/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { useUserNicknameQuery } from '@/apis/queries/useUserNicknameQuery';
import { ReactComponent as KakaoIcon } from '@/assets/kakao.svg';
import { ReactComponent as NaverIcon } from '@/assets/naver.svg';
import AuthLoginButton from '@/domain/login/components/AuthLoginButton';

export default function Login() {
const { data } = useUserNicknameQuery({ nickname: 'test' });
console.log(data);
return (
<main className="bg-white flex flex-col justify-center items-center">
<div className="text-[64px] mb-[120px] font-extrabold">LOGO</div>
Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,6 @@
],
"exclude": [
"node_modules",
"src/apis/apiGenerator"
]
}
27 changes: 20 additions & 7 deletions vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
import { defineConfig } from 'vite';
import { defineConfig, loadEnv } from 'vite';
import svgr from 'vite-plugin-svgr';
import tsconfigPaths from 'vite-tsconfig-paths';

import react from '@vitejs/plugin-react';

export default defineConfig({
plugins: [svgr(), react(), tsconfigPaths()],
build: {
outDir: 'dist',
},
});
export default ({ mode }: { mode: string }) => {
process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };
return defineConfig({
plugins: [svgr(), react(), tsconfigPaths()],
build: {
outDir: 'dist',
},
server: {
port: 8080,
proxy: {
'/api': {
target: process.env.VITE_API_URL,
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
});
};
Loading