feat : 메인 "새 글" 창을 IT 헤드라인(GeekNews)·날씨(Open-Meteo) 창으로 교체
SpecialSource Frontend (React) CD / deploy (push) Successful in 14s

- IT 헤드라인: 백엔드 /api/headlines (로그인 불필요), 줄 클릭 시 새 탭으로 열기
- 날씨: 접속자 위치(거부·무응답 시 서울) 기준 지금/오늘/내일, 좌표는 약 1km 단위로만 전송
- 페이지를 연 동안 한 번만 불러옴
- study-notes 9번 추가 (백엔드 메모리 캐시)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
headporterandClaude Opus 5.5 committed 2026-11-25 16:47:37 +09:00
1 parent 73ad4705bc
commit 4bbf5c1ba4
7 files changed
+160 -29

No files matched your search

+32 -1
View File
@@ -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로 덮어쓰기 가능 // 개발은 로컬 백엔드 직접 호출, 운영(nginx)은 같은 도메인의 /api 프록시. NEXT_PUBLIC_API_URL로 덮어쓰기 가능
export const 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<Board[]> => export const fetchBoards = async (token: string): Promise<Board[]> =>
(await call("/api/scraped-posts/boards", token)).json(); (await call("/api/scraped-posts/boards", token)).json();
/** IT 헤드라인 (GeekNews). 백엔드가 30분마다 피드를 읽어 둠. 로그인 없이 볼 수 있음 */
export async function fetchHeadlines(): Promise<Headline[]> {
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<Weather> {
const at = await new Promise<typeof SEOUL>((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}&current=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) => export const markViewed = (token: string, id: number) =>
call(`/api/scraped-posts/${id}/view`, token, { method: "POST" }); call(`/api/scraped-posts/${id}/view`, token, { method: "POST" });
+1 -10
View File
@@ -225,16 +225,7 @@ export default function BbsTerminal() {
{pulling && <div className={styles.pull}>↓ 놓으면 새로고침</div>} {pulling && <div className={styles.pull}>↓ 놓으면 새로고침</div>}
<div className={styles.grid}> <div className={styles.grid}>
{state.screen === "main" && ( {state.screen === "main" && (
<MainMenu <MainMenu feed={state.feed} loggedIn={!!state.user} onSelect={submitFromClick} />
feed={state.feed}
loggedIn={!!state.user}
onSelect={submitFromClick}
onOpenPost={(num) => {
// 메인에서 숫자는 메뉴 번호라서, 게시판으로 옮긴 뒤 글 번호를 실행
dispatch({ screen: "list", list: "board", board: null });
dispatch(String(num));
}}
/>
)} )}
{state.screen === "login" && ( {state.screen === "login" && (
<LoginForm onSuccess={(user, token) => dispatch({ screen: "main", user, token })} /> <LoginForm onSuccess={(user, token) => dispatch({ screen: "main", user, token })} />
+80
View File
@@ -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<Headline[]> | null = null;
let weatherOnce: Promise<Weather> | 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<Headline[] | null>(null);
const [weather, setWeather] = useState<Weather | null>(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 (
<div className={styles.stack}>
<section className={styles.win}>
<span className={styles.cap}>═ IT 헤드라인 ═</span>
{news ? (
<ul className={`${styles.menu} ${styles.news}`}>
{news.map((h) => (
<li key={h.link}>
<a href={h.link} target="_blank" rel="noreferrer">
· {h.title}
</a>
</li>
))}
</ul>
) : (
<div className={styles.dim}>{error.news ? "헤드라인을 불러오지 못했습니다." : "불러오는 중..."}</div>
)}
<div className={styles.footer}>출처: GeekNews · 줄을 누르면 새 탭으로 열림</div>
</section>
<section className={styles.win}>
<span className={styles.cap}>═ 날씨{weather && ` · ${weather.place}`} ═</span>
{weather ? (
<table className={styles.tbl}>
<tbody>
<tr>
<td className={styles.accent}>지금</td>
<td>{sky(weather.now.code)}</td>
<td className={styles.title}>{deg(weather.now.temp)}</td>
</tr>
{weather.days.map((d, i) => (
<tr key={i}>
<td className={styles.accent}>{i === 0 ? "오늘" : "내일"}</td>
<td>{sky(d.code)}</td>
<td className={styles.title}>
{deg(d.min)} / {deg(d.max)}
</td>
</tr>
))}
</tbody>
</table>
) : (
<div className={styles.dim}>{error.weather ? "날씨를 불러오지 못했습니다." : "위치 확인 중..."}</div>
)}
</section>
</div>
);
}
+3 -18
View File
@@ -1,13 +1,12 @@
import { MENU } from "../constants"; import { MENU } from "../constants";
import type { Feed } from "../types"; import type { Feed } from "../types";
import { PostTable } from "./PostList"; import MainInfo from "./MainInfo";
import styles from "./bbs.module.css"; import styles from "./bbs.module.css";
interface Props { interface Props {
feed: Feed | null; feed: Feed | null;
loggedIn: boolean; loggedIn: boolean;
onSelect: (cmd: string) => void; onSelect: (cmd: string) => void;
onOpenPost: (id: number) => void;
} }
// 영문 ASCII만 사용: ╔═╗ 같은 박스 문자는 한글 글꼴에서 폭이 달라져 줄이 어긋남 // 영문 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; // 메인에서는 스크랩 게시판 전체(안 읽은 글)를 불러옴 const board = feed?.kind === "board" && !feed.board ? feed : null; // 메인에서는 스크랩 게시판 전체(안 읽은 글)를 불러옴
return ( return (
@@ -51,21 +50,7 @@ export default function MainMenu({ feed, loggedIn, onSelect, onOpenPost }: Props
</ul> </ul>
</section> </section>
<section className={styles.win}> <MainInfo />
<span className={styles.cap}>═ 새 글 ═</span>
{!loggedIn ? (
<div className={styles.dim}>로그인하면 스크랩된 새 글이 보입니다.</div>
) : !board ? (
<div className={styles.dim}>불러오는 중...</div>
) : board.posts.length === 0 ? (
<div className={styles.dim}>새 글을 모두 읽었습니다.</div>
) : (
<PostTable posts={board.posts.slice(0, 5)} onSelect={onOpenPost} />
)}
<div className={styles.footer}>
줄을 누르면 바로 읽기 · <b>2</b>=게시판 전체
</div>
</section>
</> </>
); );
} }
@@ -66,6 +66,10 @@
.menu li .en { margin-left: auto; } .menu li .en { margin-left: auto; }
.menu li:hover, .menu li:hover * { background: var(--bbs-sel); color: var(--bbs-bar-fg); } .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 { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
.tbl th { .tbl th {
+13
View File
@@ -30,6 +30,19 @@ export type Palette = "blue" | "green" | "amber";
export type Screen = "main" | "list" | "post" | "login"; export type Screen = "main" | "list" | "post" | "login";
export type ListKind = "board" | "viewed"; 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와 같은 모양 (스크랩 대상 게시판 하나) */ /** 백엔드 BoardSummaryResponse와 같은 모양 (스크랩 대상 게시판 하나) */
export interface Board { export interface Board {
boardKey: string; boardKey: string;
+27
View File
@@ -194,3 +194,30 @@ CLAUDE.md, 프로젝트 메모리, 자동 메모리(~/.claude), 세션 기록, g
### 키워드 ### 키워드
CLAUDE.md, ~/.claude, 자동 메모리, CLAUDE.local.md, 공유 범위 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