Skip to content

Commit

Permalink
[fix] useApi 변경 및 환경변수 추가 (#147)
Browse files Browse the repository at this point in the history
* fix : useApi 헤더 받을 수 있게 변경

* fix : useApi 로 변경

* fix : api url 환경변수로 변경

* feat : credentials 추가

* feat : fetch -> useApi로 변경

* fix : baseURL 추가

* fix : dockerfile에 env 추가
  • Loading branch information
ChoiSangwon authored Dec 6, 2023
1 parent c5d2a4d commit 9263022
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 94 deletions.
2 changes: 1 addition & 1 deletion client/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ FROM --platform=linux/amd64 node:lts-alpine as build-stage
WORKDIR /app

# 의존성 파일 복사 및 설치
COPY package.json yarn.lock ./
COPY package.json yarn.lock .env ./
RUN yarn install && yarn global add typescript

# 소스 코드 복사
Expand Down
42 changes: 22 additions & 20 deletions client/src/components/Modal/LoginModal/LoginModal.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import useApi from '@/hooks/useApi'
import * as styles from './LoginModal.styles'
import { ThemeFlag } from '@/types/theme'

Expand All @@ -7,28 +8,29 @@ interface LoginModalProps {
}

const LoginModal = ({ onCancle, currentTheme }: LoginModalProps) => {
const [response, fetchApi] = useApi<{ userId: string; nickname: string }>()

const onLoginImage = () => {
const popup = window.open('https://api.gbs-live.site/oauth/login/naver', '_blank', 'menubar=no, toolbar=no, width=500, height=600')

const popupEvent = () => {
if (popup !== null && popup.closed == true) {
fetch('https://api.gbs-live.site/users/me/', { method: 'GET', credentials: 'include' })
.then((res) => {
if (res.ok === true) {
return res.json()
} else {
throw new Error('Login Failed')
}
})
.then((res) => {
const userId = res.userId
const userNickname = res.nickname

localStorage.setItem('user', JSON.stringify({ id: userId, nickname: userNickname }))
const popup = window.open(`${import.meta.env.VITE_API_URL}` + '/oauth/login/naver', '_blank', 'menubar=no, toolbar=no, width=500, height=600')

const popupEvent = async () => {
if (popup !== null && popup.closed === true) {
try {
await fetchApi('GET', '/users/me/', undefined, { credentials: 'include' })

if (response.data) {
const { userId, nickname } = response.data

localStorage.setItem('user', JSON.stringify({ id: userId, nickname: nickname }))
window.location.reload()
})
.catch((err) => console.error(err))
.finally(() => window.removeEventListener('focus', popupEvent))
} else {
throw new Error('Login Failed')
}
} catch (error) {
console.error(response.error || error)
} finally {
window.removeEventListener('focus', popupEvent)
}
}
}

Expand Down
101 changes: 34 additions & 67 deletions client/src/components/Modal/SettingModal/SettingModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as styles from './SettingModal.styles'
import { ThemeFlag } from '@/types/theme'
import { themeState } from '@/states/theme'
import { userState } from '@/states/user'
import useApi from '@/hooks/useApi'

interface SettingModalProps {
onConfirm: () => void
Expand All @@ -16,13 +17,14 @@ const SettingModal = ({ onConfirm }: SettingModalProps) => {
const [id, setId] = useState<string>(user.id)
const [nickname, setNickname] = useState<string>(user.nickname)
const [streamKey, setStreamKey] = useState<string>('')
const [response, fetchApi] = useApi()

const onToggleContainer = () => {
setTheme(isDarkMode ? ThemeFlag.light : ThemeFlag.dark)
localStorage.setItem('theme', `${currentTheme}`)
}

const onIdInputButton = () => {
const onIdInputButton = async () => {
if (id.trim() === '') {
alert('올바른 ID를 입력해주세요.')
setId(user.id)
Expand All @@ -33,34 +35,19 @@ const SettingModal = ({ onConfirm }: SettingModalProps) => {

return
}

fetch('https://api.gbs-live.site/users/', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ nickname: user.nickname, userId: id.trim() }),
credentials: 'include',
})
.then((res) => {
if (res.ok === true) {
return res.json()
} else {
throw new Error('Save Failed')
}
})
.then((res) => {
const userId = res.userId
const userNickname = res.nickname

alert('ID가 저장되었습니다.')
setUser({ id: userId, nickname: userNickname })
localStorage.setItem('user', JSON.stringify({ id: userId, nickname: userNickname }))
})
.catch((err) => console.error(err))
await fetchApi('PATCH', '/users/', { nickname: user.nickname, userId: id.trim() })

if (response.data) {
const { userId, nickname } = response.data
alert('ID가 저장되었습니다.')
setUser({ id: userId, nickname: nickname })
localStorage.setItem('user', JSON.stringify({ id: userId, nickname: nickname }))
} else {
console.log(response.error)
}
}

const onNicknameInputButton = () => {
const onNicknameInputButton = async () => {
if (nickname.trim() === '') {
alert('올바른 닉네임을 입력해주세요.')
setNickname(user.nickname)
Expand All @@ -71,52 +58,32 @@ const SettingModal = ({ onConfirm }: SettingModalProps) => {

return
}
await fetchApi('PATCH', '/users/', { nickname: nickname.trim(), userId: user.id })

if (response.data) {
const { userId, nickname } = response.data
alert('닉네임이 저장되었습니다.')
setUser({ id: userId, nickname: nickname })
localStorage.setItem('user', JSON.stringify({ id: userId, nickname: nickname }))
} else {
console.log(response.error)
}
}

fetch('https://api.gbs-live.site/users/', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ nickname: nickname.trim(), userId: user.id }),
credentials: 'include',
})
.then((res) => {
if (res.ok === true) {
return res.json()
} else {
throw new Error('Save Failed')
}
})
.then((res) => {
const userId = res.userId
const userNickname = res.nickname
const onKeyInputButton = async () => {
await fetchApi('GET', '/stream-keys/me/')

alert('닉네임이 저장되었습니다.')
setUser({ id: userId, nickname: userNickname })
localStorage.setItem('user', JSON.stringify({ id: userId, nickname: userNickname }))
if (response.data) {
const { streamKey } = response.data
setStreamKey(streamKey)
navigator.clipboard.writeText(streamKey).then(() => {
alert('방송 비밀 키가 클립보드에 복사되었습니다.')
})
.catch((err) => console.error(err))
}

const onKeyInputButton = () => {
navigator.clipboard.writeText(streamKey).then(() => {
alert('방송 비밀 키가 클립보드에 복사되었습니다.')
})
}
}

useEffect(() => {
fetch('https://api.gbs-live.site/stream-keys/me/', { method: 'GET', credentials: 'include' })
.then((res) => {
if (res.ok === true) {
return res.json()
} else {
throw new Error('Get Failed')
}
})
.then((res) => {
setStreamKey(res.streamKey)
})
.catch((err) => console.error(err))
onKeyInputButton()
}, [])

return (
Expand Down
17 changes: 11 additions & 6 deletions client/src/hooks/useApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,30 @@ interface ApiResponse<T> {
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function useApi<T = any>(): [ApiResponse<T>, (method: string, url: string, requestBody?: object) => Promise<void>] {
function useApi<T = any>(): [ApiResponse<T>, (method: string, url: string, requestBody?: object, customHeaders?: HeadersInit) => Promise<void>] {
const [response, setResponse] = useState<ApiResponse<T>>({
data: null,
isLoading: false,
error: null,
})

const baseURL = `${import.meta.env.VITE_API}`
const baseURL = `${import.meta.env.VITE_API_URL}`

const fetchApi = async (method: string, url: string, requestBody?: object): Promise<void> => {
const fetchApi = async (method: string, url: string, requestBody?: object, customHeaders?: HeadersInit): Promise<void> => {
setResponse({ ...response, isLoading: true })

const defaultHeaders: HeadersInit = {
'Content-Type': 'application/json',
}

const headers = customHeaders || defaultHeaders

try {
const response = await fetch(baseURL + url, {
method: method,
headers: {
'Content-Type': 'application/json',
},
headers: headers,
body: requestBody ? JSON.stringify(requestBody) : null,
credentials: 'include',
})

if (!response.ok) {
Expand Down

0 comments on commit 9263022

Please sign in to comment.