Files
contact-front/src/store/list-job-tracker.ts

98 lines
3.8 KiB
TypeScript

'use client'
import { useSyncExternalStore } from 'react'
import { getLocalStorage, setLocalStorage } from '@/store/storage/secure-storage'
import { StorageKeys } from '@/store/storage/storage-keys'
import { isListJobType, type ListJobType } from '@/types/list-job'
/**
* 사용자가 요청한 "현재" 비동기 작업 기록. 사용자·프로젝트·jobType별로 1건만 유지한다.
* 완료 상태를 표시한 다이얼로그를 사용자가 닫으면(확인) 기록을 지운다.
*/
export type TrackedListJob = {
userId: string
prjctIdx: number
jobType: ListJobType
jobKey: string
savedAt: number
/** 완료 toast를 이미 띄웠는지. 새로고침 후 중복 알림을 막는다. */
notified: boolean
}
// 다른 브라우저에서 이미 확인했을 수 있어 오래된 기록은 버린다.
const TTL_MS = 24 * 60 * 60 * 1000
const CHANGE_EVENT = 'kri:list-jobs-change'
const EMPTY: TrackedListJob[] = []
let cache: TrackedListJob[] | null = null
const isTrackedListJob = (value: unknown): value is TrackedListJob => {
if (!value || typeof value !== 'object') return false
const job = value as Record<string, unknown>
return typeof job.userId === 'string' && job.userId.length > 0
&& typeof job.prjctIdx === 'number' && Number.isInteger(job.prjctIdx) && job.prjctIdx > 0
&& isListJobType(job.jobType)
&& typeof job.jobKey === 'string' && /^[a-f0-9]{32}$/.test(job.jobKey)
&& typeof job.savedAt === 'number' && typeof job.notified === 'boolean'
}
const read = (): TrackedListJob[] => {
const stored = getLocalStorage<unknown>(StorageKeys.ListJobs)
if (!Array.isArray(stored)) return EMPTY
const now = Date.now()
return stored.filter(isTrackedListJob).filter((job) => now - job.savedAt < TTL_MS)
}
const write = (jobs: TrackedListJob[]) => {
setLocalStorage(StorageKeys.ListJobs, jobs)
cache = jobs
window.dispatchEvent(new Event(CHANGE_EVENT))
}
export const getTrackedListJobs = (): TrackedListJob[] => {
if (typeof window === 'undefined') return EMPTY
if (cache === null) cache = read()
return cache
}
export const trackListJob = (entry: Pick<TrackedListJob, 'userId' | 'prjctIdx' | 'jobType' | 'jobKey'>) => {
const jobs = getTrackedListJobs()
if (jobs.some((job) => job.jobKey === entry.jobKey)) return
write([
...jobs.filter((job) => !(job.userId === entry.userId && job.prjctIdx === entry.prjctIdx && job.jobType === entry.jobType)),
{ ...entry, savedAt: Date.now(), notified: false },
])
}
/** 아직 알리지 않은 기록이면 알림 처리하고 true를 반환한다. 중복 toast 방지용. */
export const markListJobNotified = (jobKey: string) => {
const jobs = getTrackedListJobs()
if (!jobs.some((job) => job.jobKey === jobKey && !job.notified)) return false
write(jobs.map((job) => (job.jobKey === jobKey ? { ...job, notified: true } : job)))
return true
}
export const untrackListJob = (jobKey: string) => {
const jobs = getTrackedListJobs()
if (!jobs.some((job) => job.jobKey === jobKey)) return
write(jobs.filter((job) => job.jobKey !== jobKey))
}
export const findTrackedListJob = (jobs: TrackedListJob[], userId: string, prjctIdx: number, jobType: ListJobType) =>
jobs.find((job) => job.userId === userId && job.prjctIdx === prjctIdx && job.jobType === jobType)
const subscribe = (onChange: () => void) => {
const handleStorage = (event: StorageEvent) => {
if (event.key !== null && event.key !== StorageKeys.ListJobs) return
cache = null
onChange()
}
window.addEventListener(CHANGE_EVENT, onChange)
window.addEventListener('storage', handleStorage)
return () => {
window.removeEventListener(CHANGE_EVENT, onChange)
window.removeEventListener('storage', handleStorage)
}
}
export const useTrackedListJobs = () => useSyncExternalStore(subscribe, getTrackedListJobs, () => EMPTY)