Limit unseen notifs query

This commit is contained in:
Ian Philips 2022-07-07 09:58:07 -06:00
parent 8b18cd1a26
commit c387dc2cb1
2 changed files with 21 additions and 12 deletions

View File

@ -25,10 +25,7 @@ export function usePreferredGroupedNotifications(privateUser: PrivateUser) {
const [notifications, setNotifications] = useState<Notification[]>([])
const key = `notifications-${privateUser.id}-all`
const result = useFirestoreQuery(
[key],
getNotificationsQuery(privateUser.id, false)
)
const result = useFirestoreQuery([key], getNotificationsQuery(privateUser.id))
useEffect(() => {
if (result.isLoading) return
if (!result.data) return setNotifications([])

View File

@ -1,17 +1,27 @@
import { collection, orderBy, query, where } from 'firebase/firestore'
import { collection, limit, orderBy, query, where } from 'firebase/firestore'
import { Notification } from 'common/notification'
import { db } from 'web/lib/firebase/init'
import { listenForValues } from 'web/lib/firebase/utils'
import { NOTIFICATIONS_PER_PAGE } from 'web/pages/notifications'
export function getNotificationsQuery(userId: string, unseenOnly?: boolean) {
export function getNotificationsQuery(
userId: string,
unseenOnlyOptions?: { unseenOnly: boolean; limit: number }
) {
const notifsCollection = collection(db, `/users/${userId}/notifications`)
if (unseenOnly)
if (unseenOnlyOptions?.unseenOnly)
return query(
notifsCollection,
where('isSeen', '==', false),
orderBy('createdTime', 'desc')
orderBy('createdTime', 'desc'),
limit(unseenOnlyOptions.limit)
)
return query(notifsCollection, orderBy('createdTime', 'desc'))
return query(
notifsCollection,
orderBy('createdTime', 'desc'),
// Nobody's going through 10 pages of notifications, right?
limit(NOTIFICATIONS_PER_PAGE * 10)
)
}
export function listenForNotifications(
@ -20,11 +30,13 @@ export function listenForNotifications(
unseenOnly?: boolean
) {
return listenForValues<Notification>(
getNotificationsQuery(userId, unseenOnly),
getNotificationsQuery(
userId,
unseenOnly ? { unseenOnly, limit: NOTIFICATIONS_PER_PAGE } : undefined
),
(notifs) => {
notifs.sort((n1, n2) => n2.createdTime - n1.createdTime)
setNotifications(notifs)
},
true
}
)
}