From d3865adcde598cdac48810f71db0ec082e9e5ccf Mon Sep 17 00:00:00 2001 From: jhynsoo Date: Thu, 23 May 2024 09:31:13 +0900 Subject: [PATCH] Refactor: refactor api calling functions --- src/api/area.js | 12 +-- src/api/article.js | 28 +++-- src/api/attraction.js | 7 +- src/api/chatbot.js | 19 ++-- src/api/comment.js | 19 ++-- src/api/member.js | 34 +++--- src/components/article/ArticleDetail.vue | 4 +- src/components/article/ArticleForm.vue | 2 +- src/components/article/ArticleList.vue | 12 +-- src/components/article/CommentForm.vue | 9 +- src/components/chatbot/TravelChatBot.vue | 4 +- src/components/users/UserLogin.vue | 1 - src/components/users/UserRegister.vue | 10 +- src/stores/attractionStore.js | 6 +- src/stores/memberStore.js | 128 ++++++++++------------- src/utils/http-commons.js | 4 +- src/utils/http-status.js | 2 +- 17 files changed, 130 insertions(+), 171 deletions(-) diff --git a/src/api/area.js b/src/api/area.js index 8d22e14..1aeec01 100644 --- a/src/api/area.js +++ b/src/api/area.js @@ -1,13 +1,11 @@ -import { localAxios } from "@/utils/http-commons"; +import { localAxios } from '@/utils/http-commons'; -const local = localAxios; - -function getSido(success, fail) { - local.get(`/area/sido`).then(success).catch(fail); +function getSido() { + return localAxios.get(`/area/sido`); } -function getGugun(sidoCode, success, fail) { - local.get(`/area/sido?sidoCode=${sidoCode}`).then(success).catch(fail); +function getGugun(sidoCode) { + return localAxios.get(`/area/gugun?sidoCode=${sidoCode}`); } export { getSido, getGugun }; diff --git a/src/api/article.js b/src/api/article.js index a876094..af4e473 100644 --- a/src/api/article.js +++ b/src/api/article.js @@ -1,31 +1,27 @@ import { localAxios } from '@/utils/http-commons'; -const local = localAxios; - -function getArticles(params,success, fail) { - //list - local.get('/article/list',{ params }).then(success).catch(fail); +function getArticles(params) { + return localAxios.get('/article/list', { params }); } -function searchArticle(keyword, success, fail) { - local.get(`/article/search?keyword=${keyword}`).then(success).catch(fail); +function searchArticle(keyword) { + return localAxios.get(`/article/search?keyword=${keyword}`); } -function getArticle(id, success, fail) { - //detail - local.get(`/article/${id}`).then(success).catch(fail); +function getArticle(id) { + return localAxios.get(`/article/${id}`); } -function updateArticle(article, id, success, fail) { - local.put(`/article/${id}`, JSON.stringify(article)).then(success).catch(fail); +function updateArticle(article, id) { + return localAxios.put(`/article/${id}`, JSON.stringify(article)); } -function deleteArticle(id, success, fail) { - local.delete(`/article/${id}`).then(success).catch(fail); +function deleteArticle(id) { + return localAxios.delete(`/article/${id}`); } -function addArticle(article, success, fail) { - local.post('/article', JSON.stringify(article)).then(success).catch(fail); +function addArticle(article) { + return localAxios.post('/article', JSON.stringify(article)); } export { getArticles, searchArticle, getArticle, updateArticle, deleteArticle, addArticle }; diff --git a/src/api/attraction.js b/src/api/attraction.js index bdd5799..75095c1 100644 --- a/src/api/attraction.js +++ b/src/api/attraction.js @@ -1,10 +1,7 @@ import { localAxios } from '@/utils/http-commons'; -const local = localAxios; - -function searchAttarctions(queryString, success, fail) { - //list - local.get(`/attraction/search?${queryString}`).then(success).catch(fail); +function searchAttarctions(queryString) { + return localAxios.get(`/attraction/search?${queryString}`); } export { searchAttarctions }; diff --git a/src/api/chatbot.js b/src/api/chatbot.js index 2feb2e9..87b8e99 100644 --- a/src/api/chatbot.js +++ b/src/api/chatbot.js @@ -1,16 +1,11 @@ import { localAxios } from '@/utils/http-commons'; -const local = localAxios; - -const sendMessageToChatGPT = async (message) => { - try { - const response = await local.post('/api/chatgpt/message', { message }); - - return response.data; - } catch (error) { - console.error('Error sending message to ChatGPT:', error); - return 'Sorry, there was an error processing your request.'; - } -}; +function sendMessageToChatGPT(message) { + return localAxios.post('/api/chatgpt/message', { message }).catch(() => { + return { + data: 'Sorry, there was an error processing your request.', + }; + }); +} export default sendMessageToChatGPT; diff --git a/src/api/comment.js b/src/api/comment.js index ced5989..cfd06a9 100644 --- a/src/api/comment.js +++ b/src/api/comment.js @@ -1,22 +1,19 @@ import { localAxios } from '@/utils/http-commons'; -const local = localAxios; - -function getComment(articleId, success, fail) { - //list - local.get(`/comment/${articleId}`).then(success).catch(fail); +function getComment(articleId) { + return localAxios.get(`/comment/${articleId}`); } -function addComment(comment, success, fail) { - local.post('/comment', JSON.stringify(comment)).then(success).catch(fail); +function addComment(comment) { + return localAxios.post('/comment', JSON.stringify(comment)); } -function updateComment(text, id, success, fail) { - local.put(`/comment/${id}`, text).then(success).catch(fail); +function updateComment(text, id) { + return localAxios.put(`/comment/${id}`, text); } -function deleteComment(id, success, fail) { - local.delete(`/comment/${id}`).then(success).catch(fail); +function deleteComment(id) { + return localAxios.delete(`/comment/${id}`); } export { getComment, addComment, updateComment, deleteComment }; diff --git a/src/api/member.js b/src/api/member.js index 93dd849..1a87743 100644 --- a/src/api/member.js +++ b/src/api/member.js @@ -1,31 +1,27 @@ -import { localAxios } from "@/utils/http-commons"; +import { localAxios } from '@/utils/http-commons'; -const local = localAxios; - -async function userConfirm(param, success, fail) { - await local.post(`/member/login`, param).then(success).catch(fail); +function userConfirm(param) { + return localAxios.post(`/member/login`, param); } -async function findByToken(userid,token, success, fail) { - // local.defaults.headers["Authorization"] = sessionStorage.getItem("accessToken"); - local.defaults.headers["Authorization"] = token - await local.get(`/member/info/${userid}`).then(success).catch(fail); +function findByToken(userid, token) { + localAxios.defaults.headers['Authorization'] = token; + return localAxios.get(`/member/info/${userid}`); } -async function tokenRegeneration(userid,token, success, fail) { - // local.defaults.headers["refreshToken"] = sessionStorage.getItem("refreshToken"); //axios header에 refresh-token 셋팅 - local.defaults.headers["refreshToken"] = token - console.log(userid) - console.log(token) - await local.post(`/member/refresh/${userid}`).then(success).catch(fail); +function tokenRegeneration(userid, token) { + localAxios.defaults.headers['refreshToken'] = token; + console.log(userid); + console.log(token); + return localAxios.post(`/member/refresh/${userid}`); } -async function logout(userid, success, fail) { - await local.get(`/member/logout/${userid}`).then(success).catch(fail); +function logout(userid) { + return localAxios.get(`/member/logout/${userid}`); } -function registMember(member, success, fail) { - local.post('/member/join',JSON.stringify(member)).then(success).catch(fail); +function registMember(member) { + localAxios.post('/member/join', JSON.stringify(member)); } export { userConfirm, findByToken, tokenRegeneration, logout, registMember }; diff --git a/src/components/article/ArticleDetail.vue b/src/components/article/ArticleDetail.vue index 70394b4..5ad8fce 100644 --- a/src/components/article/ArticleDetail.vue +++ b/src/components/article/ArticleDetail.vue @@ -12,10 +12,10 @@ const id = Number(route.params.id); const article = ref({}); const comments = ref([]); -getArticle(id, ({ data }) => { +getArticle(id).then(({ data }) => { article.value = data; }); -getComment(id, ({ data }) => { +getComment(id).then(({ data }) => { comments.value = data; }); diff --git a/src/components/article/ArticleForm.vue b/src/components/article/ArticleForm.vue index b7b514a..d18ab26 100644 --- a/src/components/article/ArticleForm.vue +++ b/src/components/article/ArticleForm.vue @@ -40,7 +40,7 @@ function handleSubmit() { text: text.value, }; - addArticle(article, ({ data }) => { + addArticle(article).then(({ data }) => { if (!isNaN(data)) { router.replace({ name: 'article', params: { id: data } }); } diff --git a/src/components/article/ArticleList.vue b/src/components/article/ArticleList.vue index 3d1bb3b..7959bb2 100644 --- a/src/components/article/ArticleList.vue +++ b/src/components/article/ArticleList.vue @@ -32,19 +32,17 @@ watch(lastElement, (el) => { }); function searchList() { - getArticles( - params, - ({ data }) => { + getArticles(params) + .then(({ data }) => { if ((data?.articles?.length ?? 0) === 0) { hasNextPage.value = false; return; } articles.value = [...articles.value, ...(data?.articles ?? [])]; - }, - (error) => { + }) + .catch((error) => { console.log(error); - } - ); + }); } searchList(); diff --git a/src/components/article/CommentForm.vue b/src/components/article/CommentForm.vue index d36146c..c4bc7be 100644 --- a/src/components/article/CommentForm.vue +++ b/src/components/article/CommentForm.vue @@ -9,8 +9,7 @@ const isActive = ref(false); const textDiv = ref(null); const text = ref(''); -function handleFocus(e) { - console.log(e); +function handleFocus() { isActive.value = true; } @@ -21,8 +20,10 @@ function handleCancel() { function handleSubmit() { console.log(id, text.value); - addComment({ id, text: text.value }); - // TODO: add api call + addComment({ id, text: text.value }).then(({ data }) => { + console.log(data); + // TODO: 댓글 추가 후 처리 + }); text.value = ''; isActive.value = false; textDiv.value.blur(); diff --git a/src/components/chatbot/TravelChatBot.vue b/src/components/chatbot/TravelChatBot.vue index 94baf86..c757003 100644 --- a/src/components/chatbot/TravelChatBot.vue +++ b/src/components/chatbot/TravelChatBot.vue @@ -17,9 +17,9 @@ function handleSubmit() { scrollRef.value.scrollTop = scrollRef.value.scrollHeight; }); sendMessageToChatGPT(userInput.value) - .then((response) => { + .then(({ data }) => { pending.value = false; - messages.value.push({ role: 'assistant', content: response }); + messages.value.push({ role: 'assistant', content: data }); }) .then(() => nextTick()) .then(() => { diff --git a/src/components/users/UserLogin.vue b/src/components/users/UserLogin.vue index 916200e..2efb4d2 100644 --- a/src/components/users/UserLogin.vue +++ b/src/components/users/UserLogin.vue @@ -22,7 +22,6 @@ const loginUser = computed(() => { }); async function handleSubmit() { - console.log('login'); await userLogin(loginUser.value); if (isLogin.value) { router.replace('/'); diff --git a/src/components/users/UserRegister.vue b/src/components/users/UserRegister.vue index 48ce0b0..6bd0b82 100644 --- a/src/components/users/UserRegister.vue +++ b/src/components/users/UserRegister.vue @@ -28,15 +28,13 @@ function handleSubmit() { if (password.value !== passwordConfirm.value) { return; } - registMember( - member.value, - (response) => { + registMember(member.value) + .then((response) => { if (response.status == 200) { router.push({ name: 'user-login' }); } - }, - (error) => console.error(error) - ); + }) + .catch((error) => console.error(error)); } diff --git a/src/stores/attractionStore.js b/src/stores/attractionStore.js index d803f36..f8e9ebb 100644 --- a/src/stores/attractionStore.js +++ b/src/stores/attractionStore.js @@ -19,10 +19,8 @@ export const useAttractionStore = defineStore('attraction', () => { page.value = 1; } const query = `${queryString.value}&page=${page.value}`; - searchAttarctions(query, ({ data }) => { - preventClear - ? (attractionList.value = [...attractionList.value, ...data]) - : (attractionList.value = data); + searchAttarctions(query).then(({ data }) => { + attractionList.value = preventClear ? [...attractionList.value, ...data] : data; }); } diff --git a/src/stores/memberStore.js b/src/stores/memberStore.js index 9ef9478..8a7602c 100644 --- a/src/stores/memberStore.js +++ b/src/stores/memberStore.js @@ -1,93 +1,79 @@ -import { computed, ref } from "vue" -import { defineStore } from "pinia" +import { computed, ref } from 'vue'; +import { defineStore } from 'pinia'; -import { userConfirm, tokenRegeneration, logout, findByToken } from "@/api/member" -import { httpStatusCode } from "@/utils/http-status" -import { jwtDecode } from "jwt-decode" +import { userConfirm, tokenRegeneration, logout, findByToken } from '@/api/member'; +import { HTTP_STATUS_CODE } from '@/utils/http-status'; +import { jwtDecode } from 'jwt-decode'; -export const useMemberStore = defineStore("memberStore", () => { - - const accessToken = ref(localStorage.getItem('accessToken')) +export const useMemberStore = defineStore('memberStore', () => { + const accessToken = ref(localStorage.getItem('accessToken')); const isLogin = computed(() => accessToken.value !== null); - const userLogin = async (loginUser) => { - await userConfirm( - loginUser, - (response) => { - if (response.status === httpStatusCode.CREATE) { - console.log("로그인 성공!!!!") - let { data } = response - accessToken.value = data["access-token"] - localStorage.setItem("accessToken", data["access-token"]) - localStorage.setItem("refreshToken", data["refresh-token"]) + async function userLogin(loginUser) { + await userConfirm(loginUser) + .then((response) => { + if (response.status === HTTP_STATUS_CODE.CREATE) { + console.log('로그인 성공!!!!'); + let { data } = response; + accessToken.value = data['access-token']; + localStorage.setItem('accessToken', data['access-token']); + localStorage.setItem('refreshToken', data['refresh-token']); } - }, - (error) => { - console.log("로그인 실패!!!!") - console.error(error) - } - ) + }) + .catch((error) => { + console.log('로그인 실패!!!!'); + console.error(error); + }); } - const isValidToken = async (token) => { + function isValidToken(token) { const { userId } = jwtDecode(token); - console.log(userId,token) - findByToken(userId,token, () => { }, (error) => { - console.log(error); - console.log("tokenRegenerate") - tokenRegenerate(); - }) + findByToken(userId, token).catch((error) => { + console.log(error); + console.log('tokenRegenerate'); + tokenRegenerate(); + }); } - - const tokenRegenerate = async () => { - const { userId } = jwtDecode(accessToken.value) + async function tokenRegenerate() { + const { userId } = jwtDecode(accessToken.value); const refreshToken = localStorage.getItem('refreshToken'); - console.log(userId) - console.log(refreshToken) - await tokenRegeneration( - userId,refreshToken, - (response) => { - if (response.status === httpStatusCode.CREATE) { - const newAccessToken = response.data["access-token"] - const newRefreshToken = response.data["refresh-token"] - localStorage.setItem("accessToken", newAccessToken) - localStorage.setItem("refreshToken", newRefreshToken) + + await tokenRegeneration(userId, refreshToken) + .then((response) => { + if (response.status === HTTP_STATUS_CODE.CREATE) { + const newAccessToken = response.data['access-token']; + const newRefreshToken = response.data['refresh-token']; + localStorage.setItem('accessToken', newAccessToken); + localStorage.setItem('refreshToken', newRefreshToken); accessToken.value = newAccessToken; } - }, - async (error) => { - if (error.response.status === httpStatusCode.UNAUTHORIZED) { + }) + .catch((error) => { + if (error.response.status === HTTP_STATUS_CODE.UNAUTHORIZED) { userLogout(); } - } - ) + }); } - const userLogout = async () => { + function userLogout() { const refreshToken = localStorage.getItem('refreshToken'); - if (!refreshToken) { - localStorage.removeItem("accessToken") - accessToken.value = null; - return - } - await logout( - refreshToken, - (response) => { - if (response.status === httpStatusCode.OK) { - accessToken.value = null - localStorage.removeItem("accessToken") - localStorage.removeItem("refreshToken") - } else { - console.error("유저 정보 없음!!!!") - } - }, - (error) => { - console.log(error) + if (!refreshToken) { + localStorage.removeItem('accessToken'); + accessToken.value = null; + return; + } + logout(refreshToken).then((response) => { + if (response.status !== HTTP_STATUS_CODE.OK) { + return; } - ) + + accessToken.value = null; + localStorage.removeItem('accessToken'); + localStorage.removeItem('refreshToken'); + }); } return { @@ -96,5 +82,5 @@ export const useMemberStore = defineStore("memberStore", () => { isValidToken, tokenRegenerate, userLogout, - } -}) + }; +}); diff --git a/src/utils/http-commons.js b/src/utils/http-commons.js index 8b35a6a..b6bee3c 100644 --- a/src/utils/http-commons.js +++ b/src/utils/http-commons.js @@ -1,10 +1,10 @@ import axios from 'axios'; const localAxios = axios.create({ - baseURL: 'http://localhost:8000', + baseURL: import.meta.env.VITE_API_BASE_URL, headers: { 'Content-type': 'application/json;charset=utf-8', - 'Access-Control-Allow-Origin': 'http://localhost:5173', + 'Access-Control-Allow-Origin': import.meta.env.VITE_ORIGIN, }, withCredentials: true, }); diff --git a/src/utils/http-status.js b/src/utils/http-status.js index c00474e..8df266a 100644 --- a/src/utils/http-status.js +++ b/src/utils/http-status.js @@ -1,6 +1,6 @@ // HTTP Status Code // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status -export const httpStatusCode = { +export const HTTP_STATUS_CODE = { OK: 200, CREATE: 201, NOCONTENT: 204,