2022-04-09 23:10:58 +00:00
|
|
|
import _ from 'lodash'
|
2022-05-01 16:36:54 +00:00
|
|
|
import { useState, useEffect } from 'react'
|
2022-04-09 23:10:58 +00:00
|
|
|
import { Bet } from '../../common/bet'
|
|
|
|
import { Comment } from '../../common/comment'
|
|
|
|
import { Contract } from '../../common/contract'
|
2022-04-21 06:00:08 +00:00
|
|
|
import { useTimeSinceFirstRender } from './use-time-since-first-render'
|
|
|
|
import { trackLatency } from '../lib/firebase/tracking'
|
2022-05-01 16:36:54 +00:00
|
|
|
import { User } from '../../common/user'
|
|
|
|
import { getUserFeed } from '../lib/firebase/users'
|
|
|
|
import { useUpdatedContracts } from './use-contracts'
|
|
|
|
import {
|
|
|
|
getRecentBetsAndComments,
|
|
|
|
getTopWeeklyContracts,
|
|
|
|
} from '../lib/firebase/contracts'
|
2022-04-09 23:10:58 +00:00
|
|
|
|
2022-05-01 16:36:54 +00:00
|
|
|
type feed = {
|
|
|
|
contract: Contract
|
|
|
|
recentBets: Bet[]
|
|
|
|
recentComments: Comment[]
|
|
|
|
}[]
|
2022-04-09 23:10:58 +00:00
|
|
|
|
2022-05-01 16:36:54 +00:00
|
|
|
export const useAlgoFeed = (user: User | null | undefined) => {
|
|
|
|
const [feed, setFeed] = useState<feed>()
|
2022-04-09 23:10:58 +00:00
|
|
|
|
2022-04-21 06:00:08 +00:00
|
|
|
const getTime = useTimeSinceFirstRender()
|
|
|
|
|
2022-04-09 23:10:58 +00:00
|
|
|
useEffect(() => {
|
2022-05-01 16:36:54 +00:00
|
|
|
if (user) {
|
|
|
|
getUserFeed(user.id).then((feed) => {
|
|
|
|
if (feed.length === 0) {
|
|
|
|
getDefaultFeed().then((feed) => setFeed(feed))
|
|
|
|
} else setFeed(feed)
|
|
|
|
|
|
|
|
trackLatency('feed', getTime())
|
|
|
|
console.log('feed load time', getTime())
|
|
|
|
})
|
2022-04-09 23:10:58 +00:00
|
|
|
}
|
2022-05-01 16:36:54 +00:00
|
|
|
}, [user?.id])
|
2022-04-09 23:10:58 +00:00
|
|
|
|
2022-05-01 16:36:54 +00:00
|
|
|
return useUpdateFeed(feed)
|
2022-04-09 23:10:58 +00:00
|
|
|
}
|
|
|
|
|
2022-05-01 16:36:54 +00:00
|
|
|
const useUpdateFeed = (feed: feed | undefined) => {
|
|
|
|
const contracts = useUpdatedContracts(feed?.map((item) => item.contract))
|
2022-04-09 23:10:58 +00:00
|
|
|
|
2022-05-01 16:36:54 +00:00
|
|
|
return feed && contracts
|
|
|
|
? feed.map(({ contract, ...other }, i) => ({
|
|
|
|
...other,
|
|
|
|
contract: contracts[i],
|
|
|
|
}))
|
|
|
|
: undefined
|
2022-04-09 23:10:58 +00:00
|
|
|
}
|
|
|
|
|
2022-05-01 16:36:54 +00:00
|
|
|
const getDefaultFeed = async () => {
|
|
|
|
const contracts = await getTopWeeklyContracts()
|
|
|
|
const feed = await Promise.all(
|
|
|
|
contracts.map((c) => getRecentBetsAndComments(c))
|
2022-04-09 23:10:58 +00:00
|
|
|
)
|
2022-05-01 16:36:54 +00:00
|
|
|
return feed
|
2022-04-09 23:10:58 +00:00
|
|
|
}
|