2022-09-02 02:38:09 +00:00
|
|
|
import { useQueryClient } from 'react-query'
|
2022-08-28 23:03:00 +00:00
|
|
|
import { useFirestoreQueryData } from '@react-query-firebase/firestore'
|
|
|
|
import { DAY_MS, HOUR_MS } from 'common/util/time'
|
2022-09-02 02:38:09 +00:00
|
|
|
import {
|
|
|
|
getPortfolioHistory,
|
|
|
|
getPortfolioHistoryQuery,
|
|
|
|
Period,
|
|
|
|
} from 'web/lib/firebase/users'
|
2022-09-01 04:59:58 +00:00
|
|
|
|
|
|
|
const getCutoff = (period: Period) => {
|
2022-08-28 23:03:00 +00:00
|
|
|
const nowRounded = Math.round(Date.now() / HOUR_MS) * HOUR_MS
|
2022-09-01 04:59:58 +00:00
|
|
|
return periodToCutoff(nowRounded, period).valueOf()
|
|
|
|
}
|
|
|
|
|
2022-09-02 02:38:09 +00:00
|
|
|
export const usePrefetchPortfolioHistory = (userId: string, period: Period) => {
|
|
|
|
const queryClient = useQueryClient()
|
2022-09-01 04:59:58 +00:00
|
|
|
const cutoff = getCutoff(period)
|
|
|
|
return queryClient.prefetchQuery(['portfolio-history', userId, cutoff], () =>
|
2022-09-02 02:38:09 +00:00
|
|
|
getPortfolioHistory(userId, cutoff)
|
2022-09-01 04:59:58 +00:00
|
|
|
)
|
|
|
|
}
|
2022-08-28 23:03:00 +00:00
|
|
|
|
2022-09-01 04:59:58 +00:00
|
|
|
export const usePortfolioHistory = (userId: string, period: Period) => {
|
|
|
|
const cutoff = getCutoff(period)
|
2022-08-28 23:03:00 +00:00
|
|
|
const result = useFirestoreQueryData(
|
|
|
|
['portfolio-history', userId, cutoff],
|
2022-08-29 21:47:19 +00:00
|
|
|
getPortfolioHistoryQuery(userId, cutoff)
|
2022-08-28 23:03:00 +00:00
|
|
|
)
|
|
|
|
return result.data
|
|
|
|
}
|
|
|
|
|
|
|
|
const periodToCutoff = (now: number, period: Period) => {
|
|
|
|
switch (period) {
|
|
|
|
case 'daily':
|
|
|
|
return now - 1 * DAY_MS
|
|
|
|
case 'weekly':
|
|
|
|
return now - 7 * DAY_MS
|
|
|
|
case 'monthly':
|
|
|
|
return now - 30 * DAY_MS
|
|
|
|
case 'allTime':
|
|
|
|
default:
|
|
|
|
return new Date(0)
|
|
|
|
}
|
|
|
|
}
|