-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBrazeDebounceMiddleware.swift
80 lines (63 loc) · 2.59 KB
/
BrazeDebounceMiddleware.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//
// BrazeDebounceMiddleware.swift
// SegmentBrazeDebounce-iOS
//
// Created by Brandon Sneed on 10/22/19.
// Copyright © 2019 Brandon Sneed. All rights reserved.
//
import Foundation
import Segment
fileprivate let __brazeIntegrationName = "Appboy"
class BrazeDebounceMiddleware: SEGMiddleware {
var previousIdentifyPayload: SEGIdentifyPayload? = nil
func context(_ context: SEGContext, next: @escaping SEGMiddlewareNext) {
var workingContext = context
// only process identify payloads.
guard let identify = workingContext.payload as? SEGIdentifyPayload else {
next(workingContext)
return
}
if shouldSendToBraze(payload: identify) {
// we don't need to do anything, it's different content.
} else {
// append to integrations such that this will not be sent to braze.
var integrations = identify.integrations
integrations[__brazeIntegrationName] = false
// provide the list of integrations to a new copy of the payload to pass along.
workingContext = workingContext.modify { (ctx) in
ctx.payload = SEGIdentifyPayload(userId: identify.userId ?? "",
anonymousId: identify.anonymousId,
traits: identify.traits,
context: identify.context,
integrations: integrations)
}
}
previousIdentifyPayload = identify
next(workingContext)
}
func shouldSendToBraze(payload: SEGIdentifyPayload) -> Bool {
// if userID has changed, send it to braze.
if payload.userId != previousIdentifyPayload?.userId {
return true
}
// if anonymousID has changed, send it to braze.
if payload.anonymousId != previousIdentifyPayload?.anonymousId {
return true
}
// if the traits haven't changed, don't send it to braze.
if traitsEqual(lhs: payload.traits, rhs: previousIdentifyPayload?.traits) {
return false
}
return true
}
func traitsEqual(lhs: [String: Any]?, rhs: [String: Any]? ) -> Bool {
var result = false
if lhs == nil && rhs == nil {
result = true
}
if let lhs = lhs, let rhs = rhs {
result = NSDictionary(dictionary: lhs).isEqual(to: rhs)
}
return result
}
}