Files
modstagram-back/utils/tagNotification.js
2026-09-24 21:03:27 +03:30

48 lines
1.6 KiB
JavaScript

const UserModel = require('../models/UserModel')
const { notifyUser } = require('./notifyUser')
const { buildStorageUrl } = require('./storageUrl')
// همون الگوی services/*Cron.js — چون این تابع مستقیم از کنترلر صدا زده می‌شه (نه یه
// جاب زمان‌بندی‌شده)، io از index.js با همین setIo تزریق می‌شه تا notifyUser بتونه
// رویداد سوکت لحظه‌ای هم بفرسته، نه فقط ردیف دیتابیس/پوش
let ioInstance = null
function setIo (io) {
ioInstance = io
}
const createTagNotifications = async ({ taggerId, taggedUserIds, postId }) => {
try {
if (!taggerId || !postId || !taggedUserIds?.length) return
const uniqueIds = [...new Set(taggedUserIds.map(String))].filter(
(id) => id !== String(taggerId)
)
if (!uniqueIds.length) return
const tagger = await UserModel.findById(taggerId).select('user_name profile_image')
const taggerUsername = tagger?.user_name || 'کاربر'
const taggerImage = buildStorageUrl(tagger?.profile_image) || undefined
await Promise.all(
uniqueIds.map((userId) =>
notifyUser(ioInstance, userId, {
type: 'post_tag',
title: taggerUsername,
description: 'در پستی از شما نام برد',
project_post_id: postId,
actor_id: taggerId,
image: taggerImage,
link: `/posts/${postId}`
})
)
)
} catch (error) {
console.error('Error creating tag notifications:', error)
}
}
module.exports = {
createTagNotifications,
setIo
}