Skip to content
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
93 changes: 90 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.7.2",
"react": "^18.2.0",
"react-cookie": "^7.1.4",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.0",
"react-scripts": "5.0.1",
Expand Down
128 changes: 128 additions & 0 deletions src/apis/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { instance, instanceWithToken } from "./axios";

// Account 관련 API들
export const signIn = async (data) => {
const response = await instance.post("/account/signin/", data);
if (response.status === 200) {
window.location.href = "/";
} else {
console.log("Error");
}
};

export const signUp = async (data) => {
const response = await instance.post("/account/signup/", data);
if (response.status === 200 || response.status === 201) {
window.location.href = "/";
} else {
console.log("Error");
}
return response;
};

export const getUser = async () => {
const response = await instanceWithToken.get("/account/info/");
if (response.status === 200) {
console.log("GET USER SUCCESS");
} else {
console.log("[ERROR] error while updating comment");
}
return response.data;
};

// POST 관련 API들
export const getPosts = async () => {
const response = await instance.get("/post/");
return response.data;
};

export const getPost = async (id) => {
const response = await instance.get(`/post/${id}/`);
return response.data;
};

export const createPost = async (data, navigate) => {
const response = await instanceWithToken.post("/post/", data);
if (response.status === 201) {
console.log("POST SUCCESS");
navigate("/");
} else {
console.log("[ERROR] error while creating post");
}
};

export const updatePost = async (id, data, navigate) => {
const response = await instanceWithToken.put(`/post/${id}/`, data);
if (response.status === 200) {
console.log("POST UPDATE SUCCESS");
navigate(-1);
} else {
console.log("[ERROR] error while updating post");
}
};

export const deletePost = async (id, navigate) => {
const response = await instanceWithToken.delete(`/post/${id}/`);
if (response.status === 204) {
console.log("DELETE SUCCESS");
navigate(-1);
} else {
console.log("[ERROR] error while deleting post");
}
};

// 과제!!
export const likePost = async (postId) => {};

// Tag 관련 API들
export const getTags = async () => {
const response = await instance.get("/tag/");
return response.data;
};

export const createTag = async (data) => {
const response = await instanceWithToken.post("/tag/", data);
if (response.status === 201) {
console.log("TAG SUCCESS");
} else {
console.log("[ERROR] error while creating tag");
}
return response; // response 받아서 그 다음 처리
};

// Comment 관련 API들
export const getComments = async (postId) => {
const response = await instance.get(`/comment/?post=${postId}`);
return response.data;
};

export const createComment = async (data) => {
const response = await instanceWithToken.post("/comment/", data);
if (response.status === 201) {
console.log("COMMENT SUCCESS");
window.location.reload(); // 새로운 코멘트 생성시 새로고침으로 반영
} else {
console.log("[ERROR] error while creating comment");
}
};

export const updateComment = async (id, data) => {
const response = await instanceWithToken.put(`/comment/${id}/`, data); // 혹시 patch로 구현했다면 .patch
if (response.status === 200) {
console.log("COMMENT UPDATE SUCCESS");
window.location.reload();
} else {
console.log("[ERROR] error while updating comment");
}
};

// 과제 !!
export const deleteComment = async (id) => {
const response = await instanceWithToken.delete(`/comment/${id}/`);
if (response.status === 204) {
console.log("COMMENT DELETE SUCCESS");
window.location.reload();
} else {
console.log("[ERROR] error while deleting comment");
}
};
52 changes: 52 additions & 0 deletions src/apis/axios.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import axios from "axios";
import { getCookie } from "../utils/cookie";

// baseURL, credential, 헤더 세팅
axios.defaults.baseURL = "http://localhost:8000/api";
axios.defaults.withCredentials = true;
axios.defaults.headers.post["Content-Type"] = "application/json";
axios.defaults.headers.common["X-CSRFToken"] = getCookie("csrftoken");

// 누구나 접근 가능한 API들
export const instance = axios.create();

// Token 있어야 접근 가능한 API들 - 얘는 토큰을 넣어줘야 해요
export const instanceWithToken = axios.create();

// instanceWithToken에는 쿠키에서 토큰을 찾고 담아줍시다!
instanceWithToken.interceptors.request.use(
// 요청을 보내기전 수행할 일
// 사실상 이번 세미나에 사용할 부분은 이거밖에 없어요
(config) => {
const accessToken = getCookie("access_token");

if (!accessToken) {
// token 없으면 리턴
return;
} else {
// token 있으면 헤더에 담아주기 (Authorization은 장고에서 JWT 토큰을 인식하는 헤더 key)
config.headers["Authorization"] = `Bearer ${accessToken}`;
}
return config;
},

// 클라이언트 요청 오류 났을 때 처리
(error) => {
// 콘솔에 찍어주고, 요청을 보내지 않고 오류를 발생시킴
console.log("Request Error!!");
return Promise.reject(error);
}
);

instanceWithToken.interceptors.response.use(
(response) => {
// 서버 응답 데이터를 프론트에 넘겨주기 전 수행할 일
console.log("Interceptor Response!!");
return response;
},
(error) => {
// 서버가 오류를 응답했을 때 처리 - 콘솔 찍어주고, 프론트에게 보내지 않고 오류를 발생시킴
console.log("Response Error!!");
return Promise.reject(error);
}
);
Loading