2022-07-07 20:41:50 +00:00
|
|
|
import { collection, limit, orderBy, query, where } from 'firebase/firestore'
|
2022-06-01 13:11:25 +00:00
|
|
|
import { Notification } from 'common/notification'
|
|
|
|
import { db } from 'web/lib/firebase/init'
|
2022-06-13 04:42:41 +00:00
|
|
|
import { listenForValues } from 'web/lib/firebase/utils'
|
2022-07-07 20:41:50 +00:00
|
|
|
import { NOTIFICATIONS_PER_PAGE } from 'web/pages/notifications'
|
2022-06-01 13:11:25 +00:00
|
|
|
|
2022-07-07 20:41:50 +00:00
|
|
|
export function getNotificationsQuery(
|
|
|
|
userId: string,
|
|
|
|
unseenOnlyOptions?: { unseenOnly: boolean; limit: number }
|
|
|
|
) {
|
2022-06-01 13:11:25 +00:00
|
|
|
const notifsCollection = collection(db, `/users/${userId}/notifications`)
|
2022-07-07 20:41:50 +00:00
|
|
|
if (unseenOnlyOptions?.unseenOnly)
|
|
|
|
return query(
|
|
|
|
notifsCollection,
|
|
|
|
where('isSeen', '==', false),
|
|
|
|
orderBy('createdTime', 'desc'),
|
|
|
|
limit(unseenOnlyOptions.limit)
|
|
|
|
)
|
|
|
|
return query(
|
|
|
|
notifsCollection,
|
|
|
|
orderBy('createdTime', 'desc'),
|
|
|
|
// Nobody's going through 10 pages of notifications, right?
|
|
|
|
limit(NOTIFICATIONS_PER_PAGE * 10)
|
|
|
|
)
|
2022-06-01 13:11:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function listenForNotifications(
|
|
|
|
userId: string,
|
|
|
|
setNotifications: (notifs: Notification[]) => void,
|
2022-07-07 20:41:50 +00:00
|
|
|
unseenOnlyOptions?: { unseenOnly: boolean; limit: number }
|
2022-06-01 13:11:25 +00:00
|
|
|
) {
|
|
|
|
return listenForValues<Notification>(
|
2022-07-07 20:41:50 +00:00
|
|
|
getNotificationsQuery(userId, unseenOnlyOptions),
|
2022-06-01 13:11:25 +00:00
|
|
|
(notifs) => {
|
|
|
|
notifs.sort((n1, n2) => n2.createdTime - n1.createdTime)
|
|
|
|
setNotifications(notifs)
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|