diff --git a/src/features/bbs/api.ts b/src/features/bbs/api.ts index 57e4e9b..8ec4d6c 100644 --- a/src/features/bbs/api.ts +++ b/src/features/bbs/api.ts @@ -1,4 +1,4 @@ -import type { Board, Feed, ListKind } from "./types"; +import type { Board, Feed, Headline, ListKind, Weather } from "./types"; // 개발은 로컬 백엔드 직접 호출, 운영(nginx)은 같은 도메인의 /api 프록시. NEXT_PUBLIC_API_URL로 덮어쓰기 가능 export const API_URL = @@ -36,5 +36,36 @@ export async function fetchFeed(token: string, kind: ListKind, board: string | n export const fetchBoards = async (token: string): Promise => (await call("/api/scraped-posts/boards", token)).json(); +/** IT 헤드라인 (GeekNews). 백엔드가 30분마다 피드를 읽어 둠. 로그인 없이 볼 수 있음 */ +export async function fetchHeadlines(): Promise { + const res = await fetch(`${API_URL}/api/headlines`); + if (!res.ok) throw new Error(`※ 서버 오류 (${res.status})`); + return res.json(); +} + +const SEOUL = { lat: 37.57, lon: 126.98, place: "서울" }; + +/** 접속자 위치(거부하거나 8초 안에 답이 없으면 서울)의 날씨. Open-Meteo: 무료·API 키 없음·브라우저에서 직접 호출 가능 */ +export async function fetchWeather(): Promise { + const at = await new Promise((resolve) => { + setTimeout(() => resolve(SEOUL), 8000); // 위치 권한 팝업을 그냥 두면 응답이 영영 안 옴 + navigator.geolocation?.getCurrentPosition( + // 소수 둘째 자리(약 1km)까지만 보냄: 날씨에는 충분하고 정확한 위치는 밖으로 안 나감 + (p) => resolve({ lat: +p.coords.latitude.toFixed(2), lon: +p.coords.longitude.toFixed(2), place: "현재 위치" }), + () => resolve(SEOUL), + { maximumAge: 30 * 60 * 1000 }, + ); + }); + const q = `latitude=${at.lat}&longitude=${at.lon}¤t=temperature_2m,weather_code&daily=weather_code,temperature_2m_max,temperature_2m_min&timezone=auto&forecast_days=2`; + const res = await fetch(`https://api.open-meteo.com/v1/forecast?${q}`); + if (!res.ok) throw new Error(`날씨 서버 오류 (${res.status})`); + const d = await res.json(); + return { + place: at.place, + now: { temp: d.current.temperature_2m, code: d.current.weather_code }, + days: [0, 1].map((i) => ({ max: d.daily.temperature_2m_max[i], min: d.daily.temperature_2m_min[i], code: d.daily.weather_code[i] })), + }; +} + export const markViewed = (token: string, id: number) => call(`/api/scraped-posts/${id}/view`, token, { method: "POST" }); diff --git a/src/features/bbs/components/BbsTerminal.tsx b/src/features/bbs/components/BbsTerminal.tsx index b5d90e2..be56222 100644 --- a/src/features/bbs/components/BbsTerminal.tsx +++ b/src/features/bbs/components/BbsTerminal.tsx @@ -225,16 +225,7 @@ export default function BbsTerminal() { {pulling &&
↓ 놓으면 새로고침
}
{state.screen === "main" && ( - { - // 메인에서 숫자는 메뉴 번호라서, 게시판으로 옮긴 뒤 글 번호를 실행 - dispatch({ screen: "list", list: "board", board: null }); - dispatch(String(num)); - }} - /> + )} {state.screen === "login" && ( dispatch({ screen: "main", user, token })} /> diff --git a/src/features/bbs/components/MainInfo.tsx b/src/features/bbs/components/MainInfo.tsx new file mode 100644 index 0000000..8e13eac --- /dev/null +++ b/src/features/bbs/components/MainInfo.tsx @@ -0,0 +1,80 @@ +import { useEffect, useState } from "react"; +import { fetchHeadlines, fetchWeather } from "../api"; +import type { Headline, Weather } from "../types"; +import styles from "./bbs.module.css"; + +// 페이지를 연 동안 한 번만 불러옴 (메인으로 돌아올 때마다 위치를 묻거나 다시 요청하지 않게) +let headlinesOnce: Promise | null = null; +let weatherOnce: Promise | null = null; + +/** WMO 날씨 코드 → 한글 (https://open-meteo.com/en/docs 의 WMO Weather interpretation codes) */ +const sky = (c: number) => + c === 0 ? "맑음" : c <= 2 ? "구름조금" : c === 3 ? "흐림" : c <= 48 ? "안개" : c <= 57 ? "이슬비" + : c <= 67 ? "비" : c <= 77 ? "눈" : c <= 82 ? "소나기" : c <= 86 ? "눈" : "뇌우"; +const deg = (t: number) => `${Math.round(t)}℃`; + +/** 메인 화면 오른쪽: IT 헤드라인 + 날씨 */ +export default function MainInfo() { + const [news, setNews] = useState(null); + const [weather, setWeather] = useState(null); + const [error, setError] = useState({ news: false, weather: false }); + + useEffect(() => { + (headlinesOnce ??= fetchHeadlines()).then(setNews).catch(() => { + headlinesOnce = null; // 실패하면 다음에 메인으로 올 때 다시 시도 + setError((e) => ({ ...e, news: true })); + }); + (weatherOnce ??= fetchWeather()).then(setWeather).catch(() => { + weatherOnce = null; + setError((e) => ({ ...e, weather: true })); + }); + }, []); + + return ( +
+
+ ═ IT 헤드라인 ═ + {news ? ( + + ) : ( +
{error.news ? "헤드라인을 불러오지 못했습니다." : "불러오는 중..."}
+ )} +
출처: GeekNews · 줄을 누르면 새 탭으로 열림
+
+ +
+ ═ 날씨{weather && ` · ${weather.place}`} ═ + {weather ? ( + + + + + + + + {weather.days.map((d, i) => ( + + + + + + ))} + +
지금{sky(weather.now.code)}{deg(weather.now.temp)}
{i === 0 ? "오늘" : "내일"}{sky(d.code)} + {deg(d.min)} / {deg(d.max)} +
+ ) : ( +
{error.weather ? "날씨를 불러오지 못했습니다." : "위치 확인 중..."}
+ )} +
+
+ ); +} diff --git a/src/features/bbs/components/MainMenu.tsx b/src/features/bbs/components/MainMenu.tsx index dacec04..d2902f0 100644 --- a/src/features/bbs/components/MainMenu.tsx +++ b/src/features/bbs/components/MainMenu.tsx @@ -1,13 +1,12 @@ import { MENU } from "../constants"; import type { Feed } from "../types"; -import { PostTable } from "./PostList"; +import MainInfo from "./MainInfo"; import styles from "./bbs.module.css"; interface Props { feed: Feed | null; loggedIn: boolean; onSelect: (cmd: string) => void; - onOpenPost: (id: number) => void; } // 영문 ASCII만 사용: ╔═╗ 같은 박스 문자는 한글 글꼴에서 폭이 달라져 줄이 어긋남 @@ -23,7 +22,7 @@ const LOGO = ''; // \__ \| (_) || |_| || /| (__ | _| // |___/ \___/ \___/ |_|_\ \___||___|`; -export default function MainMenu({ feed, loggedIn, onSelect, onOpenPost }: Props) { +export default function MainMenu({ feed, loggedIn, onSelect }: Props) { const board = feed?.kind === "board" && !feed.board ? feed : null; // 메인에서는 스크랩 게시판 전체(안 읽은 글)를 불러옴 return ( @@ -51,21 +50,7 @@ export default function MainMenu({ feed, loggedIn, onSelect, onOpenPost }: Props -
- ═ 새 글 ═ - {!loggedIn ? ( -
로그인하면 스크랩된 새 글이 보입니다.
- ) : !board ? ( -
불러오는 중...
- ) : board.posts.length === 0 ? ( -
새 글을 모두 읽었습니다.
- ) : ( - - )} -
- 줄을 누르면 바로 읽기 · 2=게시판 전체 -
-
+ ); } diff --git a/src/features/bbs/components/bbs.module.css b/src/features/bbs/components/bbs.module.css index 06706ee..ebf9666 100644 --- a/src/features/bbs/components/bbs.module.css +++ b/src/features/bbs/components/bbs.module.css @@ -66,6 +66,10 @@ .menu li .en { margin-left: auto; } .menu li:hover, .menu li:hover * { background: var(--bbs-sel); color: var(--bbs-bar-fg); } +/* 메인 오른쪽: 헤드라인·날씨 창을 세로로 쌓기 */ +.stack { display: flex; flex-direction: column; gap: 1.6em; min-width: 0; } +.news a { flex: 1; min-width: 0; color: inherit; text-decoration: none; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + /* 게시판 표 */ .tbl { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; } .tbl th { diff --git a/src/features/bbs/types.ts b/src/features/bbs/types.ts index 457e45f..421dcd5 100644 --- a/src/features/bbs/types.ts +++ b/src/features/bbs/types.ts @@ -30,6 +30,19 @@ export type Palette = "blue" | "green" | "amber"; export type Screen = "main" | "list" | "post" | "login"; export type ListKind = "board" | "viewed"; +/** 메인 화면 IT 헤드라인 (백엔드 /api/headlines) */ +export interface Headline { + title: string; + link: string; +} + +/** 메인 화면 날씨 (code = WMO 날씨 코드) */ +export interface Weather { + place: string; + now: { temp: number; code: number }; + days: { max: number; min: number; code: number }[]; // [오늘, 내일] +} + /** 백엔드 BoardSummaryResponse와 같은 모양 (스크랩 대상 게시판 하나) */ export interface Board { boardKey: string; diff --git a/study-notes.md b/study-notes.md index 12444fc..c50ebc6 100644 --- a/study-notes.md +++ b/study-notes.md @@ -194,3 +194,30 @@ CLAUDE.md, 프로젝트 메모리, 자동 메모리(~/.claude), 세션 기록, g ### 키워드 CLAUDE.md, ~/.claude, 자동 메모리, CLAUDE.local.md, 공유 범위 + +--- + +## 9. "메모리에 저장"은 어디에 저장하는 걸까? (백엔드 캐시) + +**질문:** IT 헤드라인을 30분 동안 메모리에 보관한다는데, 어느 메모리에 저장해? + +**요약:** 백엔드(Spring) 프로그램이 실행되는 동안 쓰는 **JVM 힙 메모리**의 변수에 저장한다. +DB·Redis·파일이 아니라 그냥 자바 객체의 필드라서, **서버를 재시작하면 사라지고** 다시 피드를 읽어 온다. + +### 핵심 내용 +- `HeadlineController`의 필드 `cached`(헤드라인 목록)와 `fetchedAt`(가져온 시각)이 저장 위치. +- Spring의 `@RestController`는 기본이 **싱글톤**: 서버에 객체가 딱 하나 → 모든 접속자가 같은 필드를 함께 씀. +- 요청이 오면 `fetchedAt`이 30분 안이면 `cached`를 바로 돌려주고, 지났으면 GeekNews에서 다시 읽음. +- 여러 사람이 동시에 요청해도 꼬이지 않게 메서드에 `synchronized` (한 번에 한 요청만 들어감). +- 이 방식의 한계: 재시작하면 비워짐 / 서버가 여러 대면 서버마다 따로 저장. 지금처럼 서버 한 대 + 30분 캐시면 충분. +- 프론트에도 비슷한 캐시가 있음: `MainInfo.tsx`의 `headlinesOnce`, `weatherOnce` → **브라우저 탭의 메모리**. 탭을 닫거나 새로고침하면 사라짐. + +| 저장 위치 | 사라지는 때 | 함께 쓰는 범위 | +|---|---|---| +| JVM 힙 (백엔드 필드) | 서버 재시작 | 모든 접속자 | +| 브라우저 JS 변수 | 새로고침·탭 닫기 | 그 탭 하나 | +| sessionStorage | 탭 닫기 | 그 탭 하나 | +| localStorage / DB | 직접 지울 때까지 | 그 브라우저 / 모든 접속자 | + +### 키워드 +캐시, JVM 힙, 싱글톤 빈, synchronized, TTL, 메모리 vs DB