Firebase喜欢/不喜欢系统

时间:2017-12-13 11:50:29

标签: ios swift firebase firebase-realtime-database google-cloud-functions

我在firebase数据库中为事件实现了系统。喜欢这里的计数器EventModel -> likesInfo -> likesNumber。问题是数据偏离,例如,如果两个用户快速(0.5秒)喜欢/不喜欢(反之亦然),那么可能是在测试完成后,两个用户都停止了不喜欢而且likesNumber将是1 (错误)有时差异可能是4-6个值。在一开始,我使用runTransactionBlock将其实现到应用程序中,然后我认为我会根据事件中感兴趣的用户数量来计算并使用云功能,但结果甚至比它更糟糕在申请中。我已经看到了一些示例,包括firebase示例,(one)但其中一些不适合在事件模型中存储大量数据(如果事件具有很多人喜欢。我使用的其他人,但没有积极的结果。我附上下面的代码。请告诉我如何最好地实施这个系统?

来自应用的代码

  private func likeNumber(_ eventID: String, isLike: Bool, success: ((_ isCommited: Bool) -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.global(qos: .background).async {
            let eventRef = Database.database().reference().child(self.MainPath.events.rawValue).child(eventID).child(self.SubPath.likesInfo.rawValue).child(self.SubPath.likesNumber.rawValue)

            eventRef.runTransactionBlock({ (currentData) -> TransactionResult in
                var likesNumber = currentData.value as? Int ?? 0
                debugPrint("likesNumber", likesNumber)
                if isLike {
                    likesNumber += 1
                } else {
                    likesNumber -= 1
                }

                if likesNumber < 0 {
                    likesNumber = 0
                }

                debugPrint("sumarry likesNumber", likesNumber)

                currentData.value = likesNumber

                return TransactionResult.success(withValue: currentData)
            }, andCompletionBlock: { (error, commited, snap) in
                if let _error = error {
                    debugPrint("_error", _error.localizedDescription)
                    fail?(_error)
                    return
                }

                if commited {
                    debugPrint("commited", commited)
                }
                success?(commited)
                debugPrint("snap", snap?.value ?? "")
            })
        }
    }

云功能

var functions = require('firebase-functions');
var eventManager = require('../Managers/event-manager');

module.exports = functions.database.ref('eventLikedUsers/{eventID}/{userID}').onDelete(event => {
    const eventID = event.params.eventID;

    return eventManager.incrementLikesNumber(eventID, false);
});

module.exports = functions.database.ref('eventLikedUsers/{eventID}/{userID}').onCreate(event => {
    const eventID = event.params.eventID;

    return eventManager.incrementLikesNumber(eventID, true);
});
来自EventManager

代码

exports.incrementLikesNumber = function incrementLikesNumber(eventID, isLike) {
    return new Promise((resolve, reject) => {
        const eventRef = admin.database().ref()
            .child('events')
            .child(eventID)
            .child('likesInfo')
            .child('likesNumber');

        const prom = eventRef.transaction(currentData => {
            if (isLike) {
                return (currentData || 0) + 1;
            } else {
                return (currentData || 1) - 1;
            }
        });

        return prom
            .then(() => {
                return resolve('success operation')
            }).catch(error => {
                return reject(error)
            })
    });
};

1 个答案:

答案 0 :(得分:0)

我在EventsLikeManager中为一个和一个事件做了类似/不喜欢的函数队列。例如,如果对事件id 1执行了一个函数,并且请求对事件id 1执行相同的函数,则第二个请求排队并等待第一个请求被执行。没有重构但完全正常工作的代码通过了测试。

class EventsLikeManager {

    // MARK: - Init

    private init() { }

    static let shared = EventsLikeManager()

    private let MainPath = EventsPaths.MainPath.self
    private let SubPath = EventsPaths.SubPath.self

    private let systemQueue = DispatchQueue(label: "com.myapp.EventsLikeManager.systemQueue")

    // id, time,
    private var dict = [String : [EventSystemLikeDislikeModel]]()

    // MARK: - Like actions

    func likeEvents(_ event: EventModel, success: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        guard newSystemEvent(event) else { return }
        _likeEvents(event, success: success, fail: fail)
    }

    private func _likeEvents(_ event: EventModel, success: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        FirebasePerformanceManager.shared.likeDislikeAction(true)
        DispatchQueue.global(qos: .background).async {
            if event.systemInfo.sourceIndex == EventSystemModel.Source.firebase.index {
                self.eventLikeInternalSourceAction(event, success: success, fail: fail)
            } else {
                self.eventLikeOutsourceAction(event, success: success, fail: fail)
            }
        }
    }

    private func eventLikeOutsourceAction(_ event: EventModel, success: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.global(qos: .background).async {
            Auth.auth().currentUser?.getIDTokenForcingRefresh(true, completion: { (token, error) in
                guard token != nil else { return }

                let timestamp = Date().currentTimestamp

                event.systemTimeProperties.creationTimestamp = timestamp
                event.systemTimeProperties.updateTimestamp = timestamp
                event.systemInfo.sourceIndex = EventSystemModel.Source.firebase.index

                self.createEvent(event, success: {
                    self.userLikedEvent(event.id, notExists: {                        self.likeAction(event, timestamp: timestamp, success: success, fail: fail)
                    }, success: { (likeModel) in
                        // dislike
                        self.dislikeAction(event, success: success, fail: fail)
                    }, fail: fail)
                }, fail: { (error) in

                })
            })
        }
    }

    private func eventLikeInternalSourceAction(_ event: EventModel, success: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        userLikedEvent(event.id, notExists: {
            self.likeAction(event, success: success, fail: fail)
        }, success: { (likeModel) in
            // dislike
            self.dislikeAction(event, success: success, fail: fail)
        }, fail: fail)
    }

    func createEvent(_ event: EventModel, success: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.global(qos: .background).async {
            let dispatchGroup = DispatchGroup()
            var commonError: Error?

            let eventRef = Database.database().reference().child(self.MainPath.events.rawValue).child(event.id)

            dispatchGroup.enter()
            eventRef.runTransactionBlock({ (currentData) -> TransactionResult in
                if (currentData.value as? [String : Any]) != nil {
                    debugPrint("TransactionResult.abort()")
                    return TransactionResult.abort()
                } else {
                    dispatchGroup.enter()
                    self.createEventLocation(event, success: {
                        dispatchGroup.leave()
                    }, fail: { (error) in
                        dispatchGroup.leave()
                    })

                    currentData.value = event.toJSON()
                    return TransactionResult.success(withValue: currentData)
                }
            }, andCompletionBlock: { (error, isCommited, snap) in
                commonError = error
                debugPrint("isCommited", isCommited)
                dispatchGroup.leave()
            })

            dispatchGroup.notify(queue: .global(qos: .background), execute: {
                if let error = commonError {
                    fail?(error)
                } else {
                    success?()
                }
            })
        }
    }

    private func createEventLocation(_ event: EventModel, success: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.global(qos: .background).async {
            let eventLocationRef = Database.database().reference().child(self.MainPath.eventsLocations.rawValue)

            guard let geofire = GeoFire(firebaseRef: eventLocationRef) else { return }
            let coordinate = event.location.coordinate
            let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)

            geofire.setLocation(location, forKey: event.id, withCompletionBlock: { (error) in
                if let _error = error {
                    fail?(_error)
                } else {
                    success?()
                }
            })
        }
    }

}

// MARK: - Likes' functions

extension EventsLikeManager {

    private func likeAction(_ event: EventModel, timestamp: Double? = nil, success: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.global(qos: .background).async {
            var finalTimestamp = Date().currentTimestamp

            if let _timestamp = timestamp {
                finalTimestamp = _timestamp
            }

            var commonError: Error?
            let dispatchGroup = DispatchGroup()

            dispatchGroup.enter()
            self.likeNumber(event.id, isLike: true, success: { (isCommited) in
                dispatchGroup.leave()
            }, fail: { (error) in
                commonError = error
                dispatchGroup.leave()
            })

            dispatchGroup.enter()
            self.addEventToUserList(event, timestamp: finalTimestamp, success: {
                dispatchGroup.leave()
            }, fail: { (error) in
                commonError = error
                dispatchGroup.leave()
            })

            dispatchGroup.enter()
            self.addUserToEventUsersList(event.id, timestamp: finalTimestamp, success: {
                dispatchGroup.leave()
            }, fail: { (error) in
                commonError = error
                dispatchGroup.leave()
            })

            dispatchGroup.notify(queue: .main, execute: {
                self.checkSystemEventQueue(event)
                if let error = commonError {
                    fail?(error)
                } else {
                    success?()
                }
                FirebasePerformanceManager.shared.likeDislikeAction(false)
            })
        }
    }

    private func likeNumber(_ eventID: String, isLike: Bool, success: ((_ isCommited: Bool) -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.global(qos: .background).async {
            let eventRef = Database.database().reference().child(self.MainPath.events.rawValue).child(eventID).child(self.SubPath.likesInfo.rawValue).child(self.SubPath.likesNumber.rawValue)

            eventRef.runTransactionBlock({ (currentData) -> TransactionResult in
                var likesNumber = currentData.value as? Int ?? 0
                debugPrint("likesNumber", likesNumber)
                if isLike {
                    likesNumber += 1
                } else {
                    likesNumber -= 1
                }

                if likesNumber < 0 {
                    likesNumber = 0
                }

                debugPrint("sumarry likesNumber", likesNumber)

                currentData.value = likesNumber

                return TransactionResult.success(withValue: currentData)
            }, andCompletionBlock: { (error, commited, snap) in
                if let _error = error {
                    debugPrint("_error", _error.localizedDescription)
                    fail?(_error)
                    return
                }

                if commited {
                    debugPrint("commited", commited)
                }
                success?(commited)
                debugPrint("snap", snap?.value ?? "")
            })
        }
    }

    private func addEventToUserList(_ event: EventModel, timestamp: Double, success: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.main.async {
            guard let userID = RealmManager().getCurrentUser()?.id else { return }
            DispatchQueue.global(qos: .background).async {
                let ref = Database.database().reference().child(self.MainPath.userLikedEvents.rawValue).child(userID).child(event.id)
                let eventUserLike = EventUserLikeModel(eventID: event.id, systemInfo: event.systemInfo, dateInfo: event.dateProperties, systemTimestamp: timestamp)
                let json = eventUserLike.toJSON()

                ref.setValue(json, withCompletionBlock: { (error, ref) in
                    if let _error = error {
                        fail?(_error)
                    } else {
                        success?()
                    }
                })
            }
        }
    }

    private func addUserToEventUsersList(_ eventID: String, timestamp: Double, success: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.main.async {
            guard let userID = RealmManager().getCurrentUser()?.id else { return }
            DispatchQueue.global(qos: .background).async {
                let ref = Database.database().reference().child(self.MainPath.eventLikedUsers.rawValue).child(eventID).child(userID)
                let json = ["userID" : userID, "timestamp" : timestamp] as [String : Any]

                ref.setValue(json, withCompletionBlock: { (error, ref) in
                    if let _error = error {
                        fail?(_error)
                    } else {
                        success?()
                    }
                })
            }
        }
    }

}

// MARK: - Dislikes' functions

extension EventsLikeManager {

    private func dislikeAction(_ event: EventModel, success: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.global(qos: .background).async {
            var commonError: Error?
            let dispatchGroup = DispatchGroup()

            dispatchGroup.enter()
            self.likeNumber(event.id, isLike: false, success: { (isCommited) in
                dispatchGroup.leave()
            }, fail: { (error) in
                commonError = error
                dispatchGroup.leave()
            })

            dispatchGroup.enter()
            self.removeEventFromUserList(event.id, success: {
                dispatchGroup.leave()
            }, fail: { (error) in
                commonError = error
                dispatchGroup.leave()
            })

            dispatchGroup.enter()
            self.removeUserFromEventUsersList(event.id, success: {
                dispatchGroup.leave()
            }, fail: { (error) in
                commonError = error
                dispatchGroup.leave()
            })

            dispatchGroup.notify(queue: .main, execute: {
                self.checkSystemEventQueue(event)
                if let error = commonError {
                    fail?(error)
                } else {
                    success?()
                }
                FirebasePerformanceManager.shared.likeDislikeAction(false)
            })
        }
    }

    private func removeEventFromUserList(_ eventID: String, success: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.main.async {
            guard let currentUserID = RealmManager().getCurrentUser()?.id else { return }
            DispatchQueue.global(qos: .background).async {
                let ref = Database.database().reference().child(self.MainPath.userLikedEvents.rawValue).child(currentUserID).child(eventID)

                ref.removeValue(completionBlock: { (error, ref) in
                    if let _error = error {
                        fail?(_error)
                    } else {
                        success?()
                    }
                })
            }
        }
    }

    private func removeUserFromEventUsersList(_ eventID: String, success: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.main.async {
            guard let userID = RealmManager().getCurrentUser()?.id else { return }
            DispatchQueue.global(qos: .background).async {
                let ref = Database.database().reference().child(self.MainPath.eventLikedUsers.rawValue).child(eventID).child(userID)

                ref.removeValue(completionBlock: { (error, ref) in
                    if let _error = error {
                        fail?(_error)
                    } else {
                        success?()
                    }
                })
            }
        }
    }

}

// MARK: - Check events

extension EventsLikeManager {

    private func userLikedEvent(_ eventID: String, notExists: (() -> Void)?, success: ((_ userLike: EventUserLikeModel) -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.main.async {
            guard let currentUserID = RealmManager().getCurrentUser()?.id else { return }
            DispatchQueue.global(qos: .background).async {
                let userLikedEventRef = Database.database().reference().child(self.MainPath.userLikedEvents.rawValue).child(currentUserID).child(eventID)
                userLikedEventRef.observeSingleEvent(of: .value, with: { (snap) in
                    guard snap.exists() else {
                        notExists?()
                        return
                    }
                    guard let json = snap.value as? [String : Any] else { return }
                    guard let likedEvent = Mapper<EventUserLikeModel>().map(JSON: json) else { return }
                    success?(likedEvent)
                }, withCancel: { (error) in
                    fail?(error)
                })
            }
        }
    }

}

// MARK: - Like Actions Helpers

extension EventsLikeManager {

    private func getEventbriteAdditionalInfo(_ event: EventModel, success: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        let eventbriteAPIManager = EventbriteAPIManager()
        eventbriteAPIManager.getAdditionalInfo(event, success: { (updatedEvent) in
            self.eventLikeOutsourceAction(updatedEvent, success: success, fail: fail)
        }, fail: fail)
    }

}

// MARK: - System

extension EventsLikeManager {

    private func newSystemEvent(_ event: EventModel) -> Bool {
        let timestamp = Date().currentTimestamp
        if dict[event.id] == nil {
            dict[event.id] = [EventSystemLikeDislikeModel(timestamp: timestamp)]
        } else if dict[event.id]?.count == 0 {
            dict[event.id] = [EventSystemLikeDislikeModel(timestamp: timestamp)]
        } else if var systemEvents = dict[event.id], systemEvents.count > 0 {
            debugPrint("systemEvents", systemEvents.count)
            let systemEvent = EventSystemLikeDislikeModel(timestamp: timestamp)
            systemEvents.append(systemEvent)
            dict[event.id] = systemEvents
            return false
        }
        return true
    }

    private func checkSystemEventQueue(_ event: EventModel) {
        systemQueue.sync {
            guard var array = dict[event.id] else { return }
            guard array.first != nil else { return }
            array.removeFirst()

            debugPrint("checkSystemEventQueue array.count", array.count)
            if array.count > 0 {
                dict[event.id] = array
            } else {
                dict[event.id] = nil
                return
            }
            _likeEvents(event, success: nil, fail: nil)
        }
    }

}