Refactor: refactor api calling functions

This commit is contained in:
jhynsoo 2024-05-23 09:31:13 +09:00
parent e95cde0ec2
commit d3865adcde
17 changed files with 130 additions and 171 deletions

View File

@ -1,13 +1,11 @@
import { localAxios } from "@/utils/http-commons"; import { localAxios } from '@/utils/http-commons';
const local = localAxios; function getSido() {
return localAxios.get(`/area/sido`);
function getSido(success, fail) {
local.get(`/area/sido`).then(success).catch(fail);
} }
function getGugun(sidoCode, success, fail) { function getGugun(sidoCode) {
local.get(`/area/sido?sidoCode=${sidoCode}`).then(success).catch(fail); return localAxios.get(`/area/gugun?sidoCode=${sidoCode}`);
} }
export { getSido, getGugun }; export { getSido, getGugun };

View File

@ -1,31 +1,27 @@
import { localAxios } from '@/utils/http-commons'; import { localAxios } from '@/utils/http-commons';
const local = localAxios; function getArticles(params) {
return localAxios.get('/article/list', { params });
function getArticles(params,success, fail) {
//list
local.get('/article/list',{ params }).then(success).catch(fail);
} }
function searchArticle(keyword, success, fail) { function searchArticle(keyword) {
local.get(`/article/search?keyword=${keyword}`).then(success).catch(fail); return localAxios.get(`/article/search?keyword=${keyword}`);
} }
function getArticle(id, success, fail) { function getArticle(id) {
//detail return localAxios.get(`/article/${id}`);
local.get(`/article/${id}`).then(success).catch(fail);
} }
function updateArticle(article, id, success, fail) { function updateArticle(article, id) {
local.put(`/article/${id}`, JSON.stringify(article)).then(success).catch(fail); return localAxios.put(`/article/${id}`, JSON.stringify(article));
} }
function deleteArticle(id, success, fail) { function deleteArticle(id) {
local.delete(`/article/${id}`).then(success).catch(fail); return localAxios.delete(`/article/${id}`);
} }
function addArticle(article, success, fail) { function addArticle(article) {
local.post('/article', JSON.stringify(article)).then(success).catch(fail); return localAxios.post('/article', JSON.stringify(article));
} }
export { getArticles, searchArticle, getArticle, updateArticle, deleteArticle, addArticle }; export { getArticles, searchArticle, getArticle, updateArticle, deleteArticle, addArticle };

View File

@ -1,10 +1,7 @@
import { localAxios } from '@/utils/http-commons'; import { localAxios } from '@/utils/http-commons';
const local = localAxios; function searchAttarctions(queryString) {
return localAxios.get(`/attraction/search?${queryString}`);
function searchAttarctions(queryString, success, fail) {
//list
local.get(`/attraction/search?${queryString}`).then(success).catch(fail);
} }
export { searchAttarctions }; export { searchAttarctions };

View File

@ -1,16 +1,11 @@
import { localAxios } from '@/utils/http-commons'; import { localAxios } from '@/utils/http-commons';
const local = localAxios; function sendMessageToChatGPT(message) {
return localAxios.post('/api/chatgpt/message', { message }).catch(() => {
const sendMessageToChatGPT = async (message) => { return {
try { data: 'Sorry, there was an error processing your request.',
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.';
}
};
export default sendMessageToChatGPT; export default sendMessageToChatGPT;

View File

@ -1,22 +1,19 @@
import { localAxios } from '@/utils/http-commons'; import { localAxios } from '@/utils/http-commons';
const local = localAxios; function getComment(articleId) {
return localAxios.get(`/comment/${articleId}`);
function getComment(articleId, success, fail) {
//list
local.get(`/comment/${articleId}`).then(success).catch(fail);
} }
function addComment(comment, success, fail) { function addComment(comment) {
local.post('/comment', JSON.stringify(comment)).then(success).catch(fail); return localAxios.post('/comment', JSON.stringify(comment));
} }
function updateComment(text, id, success, fail) { function updateComment(text, id) {
local.put(`/comment/${id}`, text).then(success).catch(fail); return localAxios.put(`/comment/${id}`, text);
} }
function deleteComment(id, success, fail) { function deleteComment(id) {
local.delete(`/comment/${id}`).then(success).catch(fail); return localAxios.delete(`/comment/${id}`);
} }
export { getComment, addComment, updateComment, deleteComment }; export { getComment, addComment, updateComment, deleteComment };

View File

@ -1,31 +1,27 @@
import { localAxios } from "@/utils/http-commons"; import { localAxios } from '@/utils/http-commons';
const local = localAxios; function userConfirm(param) {
return localAxios.post(`/member/login`, param);
async function userConfirm(param, success, fail) {
await local.post(`/member/login`, param).then(success).catch(fail);
} }
async function findByToken(userid,token, success, fail) { function findByToken(userid, token) {
// local.defaults.headers["Authorization"] = sessionStorage.getItem("accessToken"); localAxios.defaults.headers['Authorization'] = token;
local.defaults.headers["Authorization"] = token return localAxios.get(`/member/info/${userid}`);
await local.get(`/member/info/${userid}`).then(success).catch(fail);
} }
async function tokenRegeneration(userid,token, success, fail) { function tokenRegeneration(userid, token) {
// local.defaults.headers["refreshToken"] = sessionStorage.getItem("refreshToken"); //axios header에 refresh-token 셋팅 localAxios.defaults.headers['refreshToken'] = token;
local.defaults.headers["refreshToken"] = token console.log(userid);
console.log(userid) console.log(token);
console.log(token) return localAxios.post(`/member/refresh/${userid}`);
await local.post(`/member/refresh/${userid}`).then(success).catch(fail);
} }
async function logout(userid, success, fail) { function logout(userid) {
await local.get(`/member/logout/${userid}`).then(success).catch(fail); return localAxios.get(`/member/logout/${userid}`);
} }
function registMember(member, success, fail) { function registMember(member) {
local.post('/member/join',JSON.stringify(member)).then(success).catch(fail); localAxios.post('/member/join', JSON.stringify(member));
} }
export { userConfirm, findByToken, tokenRegeneration, logout, registMember }; export { userConfirm, findByToken, tokenRegeneration, logout, registMember };

View File

@ -12,10 +12,10 @@ const id = Number(route.params.id);
const article = ref({}); const article = ref({});
const comments = ref([]); const comments = ref([]);
getArticle(id, ({ data }) => { getArticle(id).then(({ data }) => {
article.value = data; article.value = data;
}); });
getComment(id, ({ data }) => { getComment(id).then(({ data }) => {
comments.value = data; comments.value = data;
}); });
</script> </script>

View File

@ -40,7 +40,7 @@ function handleSubmit() {
text: text.value, text: text.value,
}; };
addArticle(article, ({ data }) => { addArticle(article).then(({ data }) => {
if (!isNaN(data)) { if (!isNaN(data)) {
router.replace({ name: 'article', params: { id: data } }); router.replace({ name: 'article', params: { id: data } });
} }

View File

@ -32,19 +32,17 @@ watch(lastElement, (el) => {
}); });
function searchList() { function searchList() {
getArticles( getArticles(params)
params, .then(({ data }) => {
({ data }) => {
if ((data?.articles?.length ?? 0) === 0) { if ((data?.articles?.length ?? 0) === 0) {
hasNextPage.value = false; hasNextPage.value = false;
return; return;
} }
articles.value = [...articles.value, ...(data?.articles ?? [])]; articles.value = [...articles.value, ...(data?.articles ?? [])];
}, })
(error) => { .catch((error) => {
console.log(error); console.log(error);
} });
);
} }
searchList(); searchList();
</script> </script>

View File

@ -9,8 +9,7 @@ const isActive = ref(false);
const textDiv = ref(null); const textDiv = ref(null);
const text = ref(''); const text = ref('');
function handleFocus(e) { function handleFocus() {
console.log(e);
isActive.value = true; isActive.value = true;
} }
@ -21,8 +20,10 @@ function handleCancel() {
function handleSubmit() { function handleSubmit() {
console.log(id, text.value); console.log(id, text.value);
addComment({ id, text: text.value }); addComment({ id, text: text.value }).then(({ data }) => {
// TODO: add api call console.log(data);
// TODO:
});
text.value = ''; text.value = '';
isActive.value = false; isActive.value = false;
textDiv.value.blur(); textDiv.value.blur();

View File

@ -17,9 +17,9 @@ function handleSubmit() {
scrollRef.value.scrollTop = scrollRef.value.scrollHeight; scrollRef.value.scrollTop = scrollRef.value.scrollHeight;
}); });
sendMessageToChatGPT(userInput.value) sendMessageToChatGPT(userInput.value)
.then((response) => { .then(({ data }) => {
pending.value = false; pending.value = false;
messages.value.push({ role: 'assistant', content: response }); messages.value.push({ role: 'assistant', content: data });
}) })
.then(() => nextTick()) .then(() => nextTick())
.then(() => { .then(() => {

View File

@ -22,7 +22,6 @@ const loginUser = computed(() => {
}); });
async function handleSubmit() { async function handleSubmit() {
console.log('login');
await userLogin(loginUser.value); await userLogin(loginUser.value);
if (isLogin.value) { if (isLogin.value) {
router.replace('/'); router.replace('/');

View File

@ -28,15 +28,13 @@ function handleSubmit() {
if (password.value !== passwordConfirm.value) { if (password.value !== passwordConfirm.value) {
return; return;
} }
registMember( registMember(member.value)
member.value, .then((response) => {
(response) => {
if (response.status == 200) { if (response.status == 200) {
router.push({ name: 'user-login' }); router.push({ name: 'user-login' });
} }
}, })
(error) => console.error(error) .catch((error) => console.error(error));
);
} }
</script> </script>

View File

@ -19,10 +19,8 @@ export const useAttractionStore = defineStore('attraction', () => {
page.value = 1; page.value = 1;
} }
const query = `${queryString.value}&page=${page.value}`; const query = `${queryString.value}&page=${page.value}`;
searchAttarctions(query, ({ data }) => { searchAttarctions(query).then(({ data }) => {
preventClear attractionList.value = preventClear ? [...attractionList.value, ...data] : data;
? (attractionList.value = [...attractionList.value, ...data])
: (attractionList.value = data);
}); });
} }

View File

@ -1,93 +1,79 @@
import { computed, ref } from "vue" import { computed, ref } from 'vue';
import { defineStore } from "pinia" import { defineStore } from 'pinia';
import { userConfirm, tokenRegeneration, logout, findByToken } from "@/api/member" import { userConfirm, tokenRegeneration, logout, findByToken } from '@/api/member';
import { httpStatusCode } from "@/utils/http-status" import { HTTP_STATUS_CODE } from '@/utils/http-status';
import { jwtDecode } from "jwt-decode" import { jwtDecode } from 'jwt-decode';
export const useMemberStore = defineStore("memberStore", () => { export const useMemberStore = defineStore('memberStore', () => {
const accessToken = ref(localStorage.getItem('accessToken'));
const accessToken = ref(localStorage.getItem('accessToken'))
const isLogin = computed(() => accessToken.value !== null); const isLogin = computed(() => accessToken.value !== null);
const userLogin = async (loginUser) => { async function userLogin(loginUser) {
await userConfirm( await userConfirm(loginUser)
loginUser, .then((response) => {
(response) => { if (response.status === HTTP_STATUS_CODE.CREATE) {
if (response.status === httpStatusCode.CREATE) { console.log('로그인 성공!!!!');
console.log("로그인 성공!!!!") let { data } = response;
let { data } = response accessToken.value = data['access-token'];
accessToken.value = data["access-token"] localStorage.setItem('accessToken', data['access-token']);
localStorage.setItem("accessToken", data["access-token"]) localStorage.setItem('refreshToken', data['refresh-token']);
localStorage.setItem("refreshToken", data["refresh-token"])
} }
}, })
(error) => { .catch((error) => {
console.log("로그인 실패!!!!") console.log('로그인 실패!!!!');
console.error(error) console.error(error);
} });
)
} }
const isValidToken = async (token) => { function isValidToken(token) {
const { userId } = jwtDecode(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();
});
} }
async function tokenRegenerate() {
const tokenRegenerate = async () => { const { userId } = jwtDecode(accessToken.value);
const { userId } = jwtDecode(accessToken.value)
const refreshToken = localStorage.getItem('refreshToken'); const refreshToken = localStorage.getItem('refreshToken');
console.log(userId)
console.log(refreshToken) await tokenRegeneration(userId, refreshToken)
await tokenRegeneration( .then((response) => {
userId,refreshToken, if (response.status === HTTP_STATUS_CODE.CREATE) {
(response) => { const newAccessToken = response.data['access-token'];
if (response.status === httpStatusCode.CREATE) { const newRefreshToken = response.data['refresh-token'];
const newAccessToken = response.data["access-token"] localStorage.setItem('accessToken', newAccessToken);
const newRefreshToken = response.data["refresh-token"] localStorage.setItem('refreshToken', newRefreshToken);
localStorage.setItem("accessToken", newAccessToken)
localStorage.setItem("refreshToken", newRefreshToken)
accessToken.value = newAccessToken; accessToken.value = newAccessToken;
} }
}, })
async (error) => { .catch((error) => {
if (error.response.status === httpStatusCode.UNAUTHORIZED) { if (error.response.status === HTTP_STATUS_CODE.UNAUTHORIZED) {
userLogout(); userLogout();
} }
} });
)
} }
const userLogout = async () => { function userLogout() {
const refreshToken = localStorage.getItem('refreshToken'); 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") if (!refreshToken) {
localStorage.removeItem("refreshToken") localStorage.removeItem('accessToken');
} else { accessToken.value = null;
console.error("유저 정보 없음!!!!") return;
} }
}, logout(refreshToken).then((response) => {
(error) => { if (response.status !== HTTP_STATUS_CODE.OK) {
console.log(error) return;
} }
)
accessToken.value = null;
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
});
} }
return { return {
@ -96,5 +82,5 @@ export const useMemberStore = defineStore("memberStore", () => {
isValidToken, isValidToken,
tokenRegenerate, tokenRegenerate,
userLogout, userLogout,
} };
}) });

View File

@ -1,10 +1,10 @@
import axios from 'axios'; import axios from 'axios';
const localAxios = axios.create({ const localAxios = axios.create({
baseURL: 'http://localhost:8000', baseURL: import.meta.env.VITE_API_BASE_URL,
headers: { headers: {
'Content-type': 'application/json;charset=utf-8', '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, withCredentials: true,
}); });

View File

@ -1,6 +1,6 @@
// HTTP Status Code // HTTP Status Code
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
export const httpStatusCode = { export const HTTP_STATUS_CODE = {
OK: 200, OK: 200,
CREATE: 201, CREATE: 201,
NOCONTENT: 204, NOCONTENT: 204,