69 lines
2.2 KiB
JavaScript
69 lines
2.2 KiB
JavaScript
|
"use strict";
|
||
|
const store_user = require("../store/user.js");
|
||
|
const store_message = require("../store/message.js");
|
||
|
const utils_http = require("../utils/http.js");
|
||
|
const POLLING_INTERVAL = 6e4;
|
||
|
let pollingTimer = null;
|
||
|
const startPollingUnreadMessages = () => {
|
||
|
try {
|
||
|
const userStore = store_user.useUserStore();
|
||
|
const messageStore = store_message.useMessageStore();
|
||
|
if (!userStore.userInfo.token) {
|
||
|
console.log("用户未登录,停止轮询请求");
|
||
|
return;
|
||
|
}
|
||
|
if (pollingTimer)
|
||
|
return;
|
||
|
pollingTimer = setInterval(() => {
|
||
|
if (!userStore.userInfo.token) {
|
||
|
console.log("用户未登录,停止轮询请求");
|
||
|
stopPollingUnreadMessages();
|
||
|
return;
|
||
|
}
|
||
|
utils_http.httpGet("/notifications").then((response) => {
|
||
|
if (response.code === 200 && response.data.length > 0) {
|
||
|
console.log("未读消息:", response.data);
|
||
|
messageStore.setUnreadMessages(response.data);
|
||
|
}
|
||
|
}).catch((error) => {
|
||
|
console.error("获取未读消息失败:", error);
|
||
|
});
|
||
|
}, POLLING_INTERVAL);
|
||
|
} catch (error) {
|
||
|
console.error("Pinia 未初始化或其他错误:", error);
|
||
|
}
|
||
|
};
|
||
|
const stopPollingUnreadMessages = () => {
|
||
|
if (pollingTimer) {
|
||
|
clearInterval(pollingTimer);
|
||
|
pollingTimer = null;
|
||
|
}
|
||
|
};
|
||
|
const markMessageAsRead = (messageId) => {
|
||
|
try {
|
||
|
const userStore = store_user.useUserStore();
|
||
|
const messageStore = store_message.useMessageStore();
|
||
|
if (!userStore.userInfo.token) {
|
||
|
console.log("用户未登录,无法标记消息为已读");
|
||
|
return Promise.reject("用户未登录");
|
||
|
}
|
||
|
return utils_http.httpPost("/notifications", {}, { messageId }).then((response) => {
|
||
|
if (response.code === 200) {
|
||
|
console.log("消息已读:", messageId);
|
||
|
messageStore.markMessageAsRead(messageId);
|
||
|
}
|
||
|
}).catch((error) => {
|
||
|
console.error("标记消息为已读失败:", error);
|
||
|
});
|
||
|
} catch (error) {
|
||
|
console.error("Pinia 未初始化或其他错误:", error);
|
||
|
}
|
||
|
};
|
||
|
const notificationService = {
|
||
|
startPollingUnreadMessages,
|
||
|
stopPollingUnreadMessages,
|
||
|
markMessageAsRead
|
||
|
};
|
||
|
exports.notificationService = notificationService;
|
||
|
//# sourceMappingURL=notificationService.js.map
|