|
| 1 | +import config from "../../../config"; |
| 2 | + |
| 3 | +const API_BASE = process.env.REACT_APP_API_BASE_URL || config.API_BASE_URL; |
| 4 | + |
| 5 | +async function request(path, { token, method = "GET", headers = {}, responseType = "json" } = {}) { |
| 6 | + if (!token) { |
| 7 | + throw new Error("인증 토큰이 필요합니다. 다시 로그인해 주세요."); |
| 8 | + } |
| 9 | + |
| 10 | + const res = await fetch(`${API_BASE}${path}`, { |
| 11 | + method, |
| 12 | + headers: { |
| 13 | + ...(responseType === "json" && method !== "GET" ? { "Content-Type": "application/json" } : {}), |
| 14 | + Authorization: `Bearer ${token}`, |
| 15 | + ...headers, |
| 16 | + }, |
| 17 | + credentials: "include", |
| 18 | + }); |
| 19 | + |
| 20 | + if (!res.ok) { |
| 21 | + const text = await res.text().catch(() => ""); |
| 22 | + throw new Error(text || `HTTP ${res.status}`); |
| 23 | + } |
| 24 | + |
| 25 | + if (responseType === "text") { |
| 26 | + return res.text(); |
| 27 | + } |
| 28 | + |
| 29 | + try { |
| 30 | + return await res.json(); |
| 31 | + } catch (error) { |
| 32 | + throw new Error("서버 응답을 해석할 수 없습니다."); |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +export async function fetchMyFiles({ token }) { |
| 37 | + const data = await request("/api/file/my", { token }); |
| 38 | + |
| 39 | + if (!Array.isArray(data)) { |
| 40 | + throw new Error("파일 목록 응답이 올바르지 않습니다."); |
| 41 | + } |
| 42 | + |
| 43 | + return data; |
| 44 | +} |
| 45 | + |
| 46 | +export async function fetchFileContent({ token, fileUUID }) { |
| 47 | + if (!fileUUID) { |
| 48 | + throw new Error("파일 식별자가 필요합니다."); |
| 49 | + } |
| 50 | + |
| 51 | + const content = await request(`/api/file/${encodeURIComponent(fileUUID)}/content`, { |
| 52 | + token, |
| 53 | + responseType: "text", |
| 54 | + }); |
| 55 | + |
| 56 | + return content; |
| 57 | +} |
| 58 | + |
| 59 | +const EXTENSION_TO_LANGUAGE = { |
| 60 | + py: "python", |
| 61 | + js: "javascript", |
| 62 | + jsx: "javascript", |
| 63 | + ts: "typescript", |
| 64 | + tsx: "typescript", |
| 65 | + java: "java", |
| 66 | + c: "c", |
| 67 | + cpp: "c++", |
| 68 | + cc: "c++", |
| 69 | + cs: "csharp", |
| 70 | + go: "go", |
| 71 | + rb: "ruby", |
| 72 | + php: "php", |
| 73 | + swift: "swift", |
| 74 | + kt: "kotlin", |
| 75 | +}; |
| 76 | + |
| 77 | +export function inferLanguageFromFilename(filename = "") { |
| 78 | + const lastDot = filename.lastIndexOf("."); |
| 79 | + if (lastDot === -1 || lastDot === filename.length - 1) { |
| 80 | + return "plaintext"; |
| 81 | + } |
| 82 | + |
| 83 | + const ext = filename.slice(lastDot + 1).toLowerCase(); |
| 84 | + return EXTENSION_TO_LANGUAGE[ext] || "plaintext"; |
| 85 | +} |
0 commit comments