2023-01-13 05:40:33 +01:00
|
|
|
import { In } from "typeorm";
|
|
|
|
import { publishMainStream } from "@/services/stream.js";
|
|
|
|
import { pushNotification } from "@/services/push-notification.js";
|
|
|
|
import type { User } from "@/models/entities/user.js";
|
|
|
|
import type { Notification } from "@/models/entities/notification.js";
|
|
|
|
import { Notifications, Users } from "@/models/index.js";
|
2017-10-30 14:12:10 +01:00
|
|
|
|
2019-04-07 14:50:36 +02:00
|
|
|
export async function readNotification(
|
2023-01-13 05:40:33 +01:00
|
|
|
userId: User["id"],
|
|
|
|
notificationIds: Notification["id"][],
|
2019-04-07 14:50:36 +02:00
|
|
|
) {
|
2022-06-12 12:28:13 +02:00
|
|
|
if (notificationIds.length === 0) return;
|
|
|
|
|
2017-10-30 14:12:10 +01:00
|
|
|
// Update documents
|
2023-01-13 05:40:33 +01:00
|
|
|
const result = await Notifications.update(
|
|
|
|
{
|
|
|
|
notifieeId: userId,
|
|
|
|
id: In(notificationIds),
|
|
|
|
isRead: false,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
isRead: true,
|
|
|
|
},
|
|
|
|
);
|
2017-10-30 14:12:10 +01:00
|
|
|
|
2022-07-13 14:07:49 +02:00
|
|
|
if (result.affected === 0) return;
|
|
|
|
|
2023-01-13 05:40:33 +01:00
|
|
|
if (!(await Users.getHasUnreadNotification(userId)))
|
|
|
|
return postReadAllNotifications(userId);
|
2022-04-30 14:52:07 +02:00
|
|
|
else return postReadNotifications(userId, notificationIds);
|
2021-07-08 18:07:55 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function readNotificationByQuery(
|
2023-01-13 05:40:33 +01:00
|
|
|
userId: User["id"],
|
2022-09-06 13:54:49 +02:00
|
|
|
query: Record<string, any>,
|
2021-07-08 18:07:55 +02:00
|
|
|
) {
|
2022-07-09 11:18:39 +02:00
|
|
|
const notificationIds = await Notifications.findBy({
|
2021-07-08 18:07:55 +02:00
|
|
|
...query,
|
|
|
|
notifieeId: userId,
|
2021-12-09 15:58:30 +01:00
|
|
|
isRead: false,
|
2023-01-13 05:40:33 +01:00
|
|
|
}).then((notifications) =>
|
|
|
|
notifications.map((notification) => notification.id),
|
|
|
|
);
|
2022-04-30 14:52:07 +02:00
|
|
|
|
|
|
|
return readNotification(userId, notificationIds);
|
|
|
|
}
|
2021-07-08 18:07:55 +02:00
|
|
|
|
2023-01-13 05:40:33 +01:00
|
|
|
function postReadAllNotifications(userId: User["id"]) {
|
|
|
|
publishMainStream(userId, "readAllNotifications");
|
|
|
|
return pushNotification(userId, "readAllNotifications", undefined);
|
2021-07-08 18:07:55 +02:00
|
|
|
}
|
|
|
|
|
2023-01-13 05:40:33 +01:00
|
|
|
function postReadNotifications(
|
|
|
|
userId: User["id"],
|
|
|
|
notificationIds: Notification["id"][],
|
|
|
|
) {
|
|
|
|
publishMainStream(userId, "readNotifications", notificationIds);
|
|
|
|
return pushNotification(userId, "readNotifications", { notificationIds });
|
2019-04-07 14:50:36 +02:00
|
|
|
}
|