리프레시 관련 문제 수정 - 캐시 갱신, DB

This commit is contained in:
2026-11-16 15:10:46 +09:00
parent b04b86b493
commit b8fa96cf90
6 changed files with 129 additions and 24 deletions
+5 -2
View File
@@ -17,19 +17,22 @@
- `server/db.js` — @supabase/supabase-js 클라이언트 (gus/dongs/poles 테이블, 전부 async)
- `server/vworld.js` — VWorld `GetFeature` 조회, 페이지네이션(최대 20페이지)
- `supabase-schema.sql` — Supabase SQL Editor에서 실행할 스키마
- `vite.config.js` — HTTPS 필수 (`~/.vite-key.pem`, `~/.vite-cert.pem` 요구), `/api`, `/uploads` 프록시 → :4000
- `vite.config.js` — HTTPS 사용 (`~/.vite-key.pem`, `~/.vite-cert.pem`; 없으면 openssl로 자동 생성, 경로는 `VITE_HTTPS_KEY`/`VITE_HTTPS_CERT`로 재정의 가능), `/api`, `/uploads` 프록시 → :4000
## 환경 설정 (.env)
`VWORLD_API_KEY`, `VWORLD_DOMAIN=localhost`, `PORT=4000`, `SUPABASE_URL`, `SUPABASE_SERVICE_ROLE_KEY` (서버용 `.env`)
- 클라이언트(Vite)는 `VITE_` 접두사만 노출하므로 지도 타일용 키는 `VITE_VWORLD_API_KEY`로 둔다
- `.env`는 `.gitignore`에 포함됨. 새 환경에서는 `.env.example`을 복사해 값을 채운다
## 현재 상태 (진행 중인 작업)
- 데이터베이스는 Supabase (Postgres) 사용. 기존 better-sqlite3는 제거됨.
- 스키마는 `supabase-schema.sql`을 SQL Editor에서 실행해야 함
- 서버에서 `SUPABASE_SERVICE_ROLE_KEY`를 사용 (서버가 곧 신뢰 경계)
- 클라이언트는 `/api/poles` API로 CRUD (사진은 multer로 `server/uploads/`에 저장, base64/loccalStorage 제거됨)
- `src/App.jsx:16`에 VWorld API 키가 하드코딩됨 → `import.meta.env.VITE_VWORLD_API_KEY`로 교체 필요 (키는 커밋하지 말 것)
- VWorld 지도 타일 키는 `src/App.jsx`에서 `import.meta.env.VITE_VWORLD_API_KEY`로 읽음 (하드코딩 없음, 키는 커밋하지 말 것)
- 위치 결정 우선순위: EXIF GPS → 브라우저 GPS → 마지막 알려진 위치
- dev용 VWorld 키는 `VITE_VWORLD_API_KEY`로도 넘길 수 있음 (`server/vworld.js`에서 서버 키에 대해 폴백)
+2
View File
@@ -13,3 +13,5 @@
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
echo -e 'Types: deb\nURIs: https://download.vscodium.com/debs\nSuites: vscodium\nComponents: main\nArchitectures: amd64 arm64\nSigned-by: /usr/share/keyrings/vscodium-archive-keyring.gpg' \
| sudo tee /etc/apt/sources.list.d/vscodium.sources
+20 -8
View File
@@ -109,14 +109,26 @@ export async function getPole(id) {
}
export async function getAllPoles({ gu = '', dong = '', start = '', end = '' } = {}) {
let query = supabase.from('poles').select('*').order('timestamp', { ascending: false });
if (gu) query = query.eq('gu', gu);
if (dong) query = query.eq('dong', dong);
if (start) query = query.gte('timestamp', start);
if (end) query = query.lte('timestamp', end);
const { data, error } = await query;
if (error) throw error;
return (data || []).map((p) => ({
// Supabase(PostgREST)는 한 번에 최대 1000행만 돌려주므로 페이지 단위로 모두 읽는다.
const PAGE = 1000;
const rows = [];
for (let from = 0; ; from += PAGE) {
let query = supabase
.from('poles')
.select('*')
.order('timestamp', { ascending: false })
.order('id', { ascending: true })
.range(from, from + PAGE - 1);
if (gu) query = query.eq('gu', gu);
if (dong) query = query.eq('dong', dong);
if (start) query = query.gte('timestamp', start);
if (end) query = query.lte('timestamp', end);
const { data, error } = await query;
if (error) throw error;
rows.push(...(data || []));
if (!data || data.length < PAGE) break;
}
return rows.map((p) => ({
...p,
photoUrl: p.photo_path ? `/uploads/${p.photo_path}` : null,
}));
+6
View File
@@ -23,6 +23,12 @@ const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
const app = express();
app.use(cors());
// API 응답은 항상 최신 데이터를 쓰도록 캐시를 금지한다.
// (Apache의 ExpiresDefault가 1개월 캐시를 붙이는 것을 막는다)
app.use('/api', (_req, res, next) => {
res.set('Cache-Control', 'no-store');
next();
});
app.use(express.json());
app.use('/uploads', express.static(UPLOAD_DIR));
+28 -9
View File
@@ -10,11 +10,26 @@ import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import { Style, Circle as CircleStyle, Fill, Stroke, Text } from 'ol/style';
import { fromLonLat } from 'ol/proj';
import imageCompression from 'browser-image-compression';
import exifr from 'exifr';
import './App.css';
// 사진 처리 라이브러리는 업로드 시점에만 필요하므로 동적 import로 분리한다.
// (초기 번들 크기를 줄이고, 첫 화면 로딩을 빠르게 한다)
let exifrPromise;
function loadExifr() {
exifrPromise ??= import('exifr');
return exifrPromise;
}
let imageCompressionPromise;
function loadImageCompression() {
imageCompressionPromise ??= import('browser-image-compression').then((m) => m.default);
return imageCompressionPromise;
}
const VWORLD_API_KEY = import.meta.env.VITE_VWORLD_API_KEY;
if (!VWORLD_API_KEY) {
console.warn('[vworld] VITE_VWORLD_API_KEY가 없습니다. .env에 키를 설정해야 지도 타일이 표시됩니다.');
}
const LEVEL_COLORS = { A: '#22c55e', B: '#f97316', Pole: '#a855f7' };
const LEVEL_LABELS = { A: 'A', B: 'B', Pole: 'P' };
const LEVEL_IGNORE = 'IGNORE';
@@ -192,7 +207,7 @@ function App() {
if (refreshing) return;
setRefreshing(true);
try {
const res = await fetch('/api/poles');
const res = await fetch('/api/poles', { cache: 'no-store' });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const next = await res.json();
polesRef.current = next;
@@ -415,8 +430,8 @@ function App() {
markerSource.addFeature(currentFeature);
currentLocationRef.current = currentFeature;
Promise.allSettled([
fetch('/api/poles').then((r) => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); }),
fetch('/api/all-dongs').then((r) => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); }),
fetch('/api/poles', { cache: 'no-store' }).then((r) => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); }),
fetch('/api/all-dongs', { cache: 'no-store' }).then((r) => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); }),
])
.then(([poleResult, dongResult]) => {
if (aborted) return;
@@ -507,7 +522,8 @@ function App() {
try {
const buffer = await file.arrayBuffer();
console.log('파일 타입:', file.type, '크기:', file.size, 'buffer 크기:', buffer.byteLength);
const exifData = await exifr.parse(buffer);
const { parse: parseExif } = await loadExifr();
const exifData = await parseExif(buffer);
console.log('EXIF 전체 데이터:', exifData);
if (exifData && exifData.latitude && exifData.longitude) {
lat = exifData.latitude;
@@ -550,7 +566,8 @@ function App() {
return;
}
const compressed = await imageCompression(file, {
const compressImage = await loadImageCompression();
const compressed = await compressImage(file, {
maxSizeMB: 0.5,
maxWidthOrHeight: 800,
useWebWorker: true,
@@ -610,7 +627,8 @@ function App() {
let exifTimestamp = null;
try {
const buffer = await file.arrayBuffer();
const exifData = await exifr.parse(buffer);
const { parse: parseExif } = await loadExifr();
const exifData = await parseExif(buffer);
if (exifData && exifData.latitude && exifData.longitude) {
lat = exifData.latitude;
lng = exifData.longitude;
@@ -699,7 +717,8 @@ function App() {
}
try {
const compressed = await imageCompression(prep.file, {
const compressImage = await loadImageCompression();
const compressed = await compressImage(prep.file, {
maxSizeMB: 0.5,
maxWidthOrHeight: 800,
useWebWorker: true,
+67 -4
View File
@@ -1,17 +1,80 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import fs from 'fs'
import os from 'os'
import path from 'path'
import { execFileSync } from 'child_process'
const home = os.homedir()
const keyPath = process.env.VITE_HTTPS_KEY || path.join(home, '.vite-key.pem')
const certPath = process.env.VITE_HTTPS_CERT || path.join(home, '.vite-cert.pem')
function localIPv4s() {
return Object.values(os.networkInterfaces())
.flat()
.filter((iface) => iface && iface.family === 'IPv4' && !iface.internal)
.map((iface) => iface.address)
}
// geolocation/카메라는 보안 컨텍스트에서만 동작하므로 HTTPS 인증서를 사용한다.
// 인증서가 없으면 openssl로 자체 서명 인증서를 한 번만 생성한다.
function ensureCertificates() {
if (fs.existsSync(keyPath) && fs.existsSync(certPath)) return true
const sans = ['DNS:localhost', 'IP:127.0.0.1', ...localIPv4s().map((ip) => `IP:${ip}`)]
try {
execFileSync(
'openssl',
[
'req', '-x509', '-newkey', 'rsa:2048', '-nodes',
'-keyout', keyPath,
'-out', certPath,
'-days', '3650',
'-subj', '/CN=localhost',
'-addext', `subjectAltName=${sans.join(',')}`,
],
{ stdio: 'ignore' },
)
console.log(`[vite] 자체 서명 인증서를 생성했습니다: ${keyPath}, ${certPath}`)
return true
} catch (err) {
console.warn(
`[vite] HTTPS 인증서를 찾을 수 없고 자동 생성도 실패했습니다 (${err.message}).\n` +
'[vite] HTTP로 실행합니다. 모바일에서 GPS/카메라를 쓰려면 인증서가 필요합니다:\n' +
`[vite] openssl req -x509 -newkey rsa:2048 -nodes -keyout "${keyPath}" -out "${certPath}" -days 3650 -subj "/CN=localhost" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"`,
)
return false
}
}
const https = ensureCertificates()
? { key: fs.readFileSync(keyPath), cert: fs.readFileSync(certPath) }
: undefined
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
build: {
// 지도(ol)와 React는 서로 독립적으로 캐시되도록 청크를 나눈다.
// 청크 하나가 500 kB를 넘지 않게 하기 위한 설정이기도 하다.
rolldownOptions: {
output: {
codeSplitting: {
groups: [
{ name: 'ol', test: /node_modules[\\/]ol[\\/]/, priority: 20 },
{
name: 'react',
test: /node_modules[\\/](react|react-dom|scheduler)[\\/]/,
priority: 15,
},
],
},
},
},
},
server: {
host: true,
https: {
key: fs.readFileSync(path.join(process.env.USERPROFILE, '.vite-key.pem')),
cert: fs.readFileSync(path.join(process.env.USERPROFILE, '.vite-cert.pem')),
},
https,
proxy: {
'/api': {
target: 'http://localhost:4000',