Files
o2o-weather/admin/src/cards/data.ts
T

87 lines
3.8 KiB
TypeScript

import { useQuery } from '@tanstack/react-query'
import { getWeatherToday, listIndices } from '../api/client'
import type { IndexSummary, WeatherSlot } from '../api/client'
import { RainType } from '../api/client'
/** 인스타 카드는 지역을 고르지 않고 서울(중구) 예보 하나로 만든다. 카드에 지역 이름은 나가지 않는다 */
export const BASE_REGION = '1114000000'
/** 템플릿이 쓰는 그날 데이터. 웹 화면과 대화로 만드는 이미지가 같은 값을 쓴다 */
export type CardData = {
regionCode: string
regionName: string
day: string
/** '10.21 화' */
dateLabel: string
headline: string
top3: IndexSummary[]
/** 오늘 각 전체 (점수 높은 순) — 날씨 타로가 카드로 쓴다 */
gaks: IndexSummary[]
morningC: number
maxC: number
minC: number
rainy: boolean
}
const WEEKDAY = ['일', '월', '화', '수', '목', '금', '토']
export function dateLabel(day: string) {
const d = day ? new Date(`${day}T00:00:00+09:00`) : new Date()
return `${d.getMonth() + 1}.${d.getDate()} ${WEEKDAY[d.getDay()]}`
}
/** 아침 6시~밤 9시 예보로 아침 기온·낮 최고·비 여부 */
function temps(slots: WeatherSlot[]) {
const hour = (s: WeatherSlot) => new Date(s.at).getHours()
const withTemp = slots.filter((s) => s.temp_c != null)
const day = withTemp.filter((s) => hour(s) >= 6 && hour(s) <= 21)
const t = day.length ? day : withTemp
const values = t.map((s) => s.temp_c as number)
const morning = t.find((s) => hour(s) === 6) ?? t[0]
return {
morningC: Math.round(morning?.temp_c ?? 0),
maxC: Math.round(Math.max(...values)),
minC: Math.round(Math.min(...values)),
rainy: t.some((s) => (s.rain_type != null && s.rain_type !== RainType.NONE) || (s.rain_prob ?? 0) >= 60),
}
}
type Indices = NonNullable<Awaited<ReturnType<typeof listIndices>>['data']>
type Weather = NonNullable<Awaited<ReturnType<typeof getWeatherToday>>['data']>
/** 날씨각 API 는 실패를 200 + result.success=false 로 알린다 */
function okOrThrow<T extends { result?: { success?: boolean; desc?: string } }>(data: T | undefined, what: string): T {
if (!data || data.result?.success === false) throw new Error(`${what} 을(를) 받지 못했어요 (${data?.result?.desc ?? '응답 없음'})`)
return data
}
const fetchIndices = (region: string) => listIndices({ query: { region } }).then((r) => okOrThrow(r.data, '오늘의 각'))
const fetchWeather = (region: string) => getWeatherToday({ query: { region } }).then((r) => okOrThrow(r.data, '오늘 예보'))
function buildCardData(regionCode: string, indices: Indices, weather: Weather): CardData {
const day = weather.day ?? ''
return {
regionCode,
regionName: weather.region_name ?? '',
day,
dateLabel: dateLabel(day),
headline: weather.headline ?? '',
top3: indices.top3 ?? [],
gaks: [...(indices.items ?? [])].sort((a, b) => b.score - a.score),
...temps(weather.slots ?? []),
}
}
/** 화면 밖(기획 요청)에서 같은 데이터를 받을 때 */
export async function loadCardData(regionCode = BASE_REGION) {
const [indices, weather] = await Promise.all([fetchIndices(regionCode), fetchWeather(regionCode)])
return buildCardData(regionCode, indices, weather)
}
export function useCardData(regionCode: string) {
const indices = useQuery({ queryKey: ['cards', 'indices', regionCode], queryFn: () => fetchIndices(regionCode), enabled: !!regionCode })
const weather = useQuery({ queryKey: ['cards', 'weather', regionCode], queryFn: () => fetchWeather(regionCode), enabled: !!regionCode })
const error = indices.error ?? weather.error
if (!indices.data || !weather.data) return { data: null, error, loading: indices.isLoading || weather.isLoading }
return { data: buildCardData(regionCode, indices.data, weather.data), error, loading: false }
}