func()

in internal/service/notification/notification_service.go [235:317]


func (ns *NotificationService) formatNotificationPage(ctx context.Context, notifications []*entity.Notification) (
	resp []*schema.NotificationContent, err error) {
	lang := handler.GetLangByCtx(ctx)
	enableShortID := handler.GetEnableShortID(ctx)
	userIDs := make([]string, 0)
	userMapping := make(map[string]bool)
	for _, notificationInfo := range notifications {
		item := &schema.NotificationContent{}
		if err := json.Unmarshal([]byte(notificationInfo.Content), item); err != nil {
			log.Error("NotificationContent Unmarshal Error", err.Error())
			continue
		}
		// If notification is downvote, the user info is not needed.
		if item.NotificationAction == constant.NotificationDownVotedTheQuestion ||
			item.NotificationAction == constant.NotificationDownVotedTheAnswer {
			item.UserInfo = nil
		}
		// If notification is badge, the user info is not needed and the title need to be translated.
		if item.ObjectInfo.ObjectType == constant.BadgeAwardObjectType {
			badgeName := translator.Tr(lang, item.ObjectInfo.Title)
			item.ObjectInfo.Title = translator.TrWithData(lang, constant.NotificationEarnedBadge, struct {
				BadgeName string
			}{BadgeName: badgeName})
			item.UserInfo = nil
		}

		item.ID = notificationInfo.ID
		item.NotificationAction = translator.Tr(lang, item.NotificationAction)
		item.UpdateTime = notificationInfo.UpdatedAt.Unix()
		item.IsRead = notificationInfo.IsRead == schema.NotificationRead

		if enableShortID {
			if answerID, ok := item.ObjectInfo.ObjectMap["answer"]; ok {
				if item.ObjectInfo.ObjectID == answerID {
					item.ObjectInfo.ObjectID = uid.EnShortID(item.ObjectInfo.ObjectMap["answer"])
				}
				item.ObjectInfo.ObjectMap["answer"] = uid.EnShortID(item.ObjectInfo.ObjectMap["answer"])
			}
			if questionID, ok := item.ObjectInfo.ObjectMap["question"]; ok {
				if item.ObjectInfo.ObjectID == questionID {
					item.ObjectInfo.ObjectID = uid.EnShortID(item.ObjectInfo.ObjectMap["question"])
				}
				item.ObjectInfo.ObjectMap["question"] = uid.EnShortID(item.ObjectInfo.ObjectMap["question"])
			}
		}

		if item.UserInfo != nil && !userMapping[item.UserInfo.ID] {
			userIDs = append(userIDs, item.UserInfo.ID)
			userMapping[item.UserInfo.ID] = true
		}
		resp = append(resp, item)
	}

	if len(userIDs) == 0 {
		return resp, nil
	}

	users, err := ns.userRepo.BatchGetByID(ctx, userIDs)
	if err != nil {
		log.Error(err)
		return resp, nil
	}
	userIDMapping := make(map[string]*entity.User, len(users))
	for _, user := range users {
		userIDMapping[user.ID] = user
	}
	for _, item := range resp {
		if item.UserInfo == nil {
			continue
		}
		userInfo, ok := userIDMapping[item.UserInfo.ID]
		if !ok {
			continue
		}
		if userInfo.Status == entity.UserStatusDeleted {
			item.UserInfo = &schema.UserBasicInfo{
				DisplayName: "user" + converter.DeleteUserDisplay(userInfo.ID),
				Status:      constant.UserDeleted,
			}
		}
	}
	return resp, nil
}