From aa4ef6745ad798bd7d4f05cb397ef1dd85279814 Mon Sep 17 00:00:00 2001 From: syuilo Date: Sat, 7 Jul 2018 19:19:00 +0900 Subject: Refactorng --- src/notify.ts | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/notify.ts (limited to 'src/notify.ts') diff --git a/src/notify.ts b/src/notify.ts new file mode 100644 index 0000000000..f55dea167c --- /dev/null +++ b/src/notify.ts @@ -0,0 +1,62 @@ +import * as mongo from 'mongodb'; +import Notification from './models/notification'; +import Mute from './models/mute'; +import { pack } from './models/notification'; +import stream from './stream'; +import User from './models/user'; +import pushSw from './push-sw'; + +export default ( + notifiee: mongo.ObjectID, + notifier: mongo.ObjectID, + type: string, + content?: any +) => new Promise(async (resolve, reject) => { + if (notifiee.equals(notifier)) { + return resolve(); + } + + // Create notification + const notification = await Notification.insert(Object.assign({ + createdAt: new Date(), + notifieeId: notifiee, + notifierId: notifier, + type: type, + isRead: false + }, content)); + + resolve(notification); + + const packed = await pack(notification); + + // Publish notification event + stream(notifiee, 'notification', packed); + + // Update flag + User.update({ _id: notifiee }, { + $set: { + hasUnreadNotification: true + } + }); + + // 3秒経っても(今回作成した)通知が既読にならなかったら「未読の通知がありますよ」イベントを発行する + setTimeout(async () => { + const fresh = await Notification.findOne({ _id: notification._id }, { isRead: true }); + if (!fresh.isRead) { + //#region ただしミュートしているユーザーからの通知なら無視 + const mute = await Mute.find({ + muterId: notifiee, + deletedAt: { $exists: false } + }); + const mutedUserIds = mute.map(m => m.muteeId.toString()); + if (mutedUserIds.indexOf(notifier.toString()) != -1) { + return; + } + //#endregion + + stream(notifiee, 'unread_notification', packed); + + pushSw(notifiee, 'notification', packed); + } + }, 3000); +}); -- cgit v1.2.3-freya