Skip to content

Commit d99d837

Browse files
authored
Merge pull request #97 from vazarkevych/append-user-attributes
Add support for attribute appending
2 parents 1aefb39 + adbf475 commit d99d837

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

GrowthBookTests/GrowthBookSDKBuilderTests.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,4 +254,37 @@ class GrowthBookSDKBuilderTests: XCTestCase {
254254

255255
XCTAssertEqual(2, countTrackingCallback)
256256
}
257+
258+
func testAppendAttributes() throws {
259+
let sdkInstance = GrowthBookBuilder(apiHost: testApiHost,
260+
clientKey: testClientKey,
261+
attributes: [:],
262+
trackingCallback: { _, _ in },
263+
refreshHandler: nil,
264+
backgroundSync: false).initializer()
265+
266+
267+
sdkInstance.setAttributes(attributes: ["name": "Alice"])
268+
try sdkInstance.appendAttributes(attributes: ["age": 30])
269+
270+
let result = sdkInstance.gbContext.attributes
271+
XCTAssertEqual(result["name"].stringValue, "Alice")
272+
XCTAssertEqual(result["age"].intValue, 30)
273+
274+
275+
sdkInstance.setAttributes(attributes: ["user": ["id": 1, "name": "Alice"]])
276+
try sdkInstance.appendAttributes(attributes: ["user": ["name": "Bob", "age": 25]])
277+
278+
let user = sdkInstance.gbContext.attributes["user"]
279+
XCTAssertEqual(user["id"].intValue, 1)
280+
XCTAssertEqual(user["name"].stringValue, "Bob")
281+
XCTAssertEqual(user["age"].intValue, 25)
282+
283+
284+
sdkInstance.setAttributes(attributes: ["user": ["roles": ["admin", "editor"]]])
285+
try sdkInstance.appendAttributes(attributes: ["user": ["roles": ["viewer"]]])
286+
287+
let roles = sdkInstance.gbContext.attributes["user"]["roles"].arrayValue.map { $0.stringValue }
288+
XCTAssertEqual(roles, ["admin", "editor", "viewer"])
289+
}
257290
}

Sources/CommonMain/GrowthBookSDK.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,14 @@ public struct GrowthBookModel {
307307
refreshStickyBucketService()
308308
}
309309

310+
/// Merges the provided user attributes with the existing ones.
311+
/// - Throws: `SwiftyJSON.Error.wrongType` if the top-level JSON types differ
312+
@objc public func appendAttributes(attributes: Any) throws {
313+
let updatedAttributes = try gbContext.attributes.merged(with: JSON(attributes))
314+
gbContext.attributes = updatedAttributes
315+
refreshStickyBucketService()
316+
}
317+
310318
@objc public func setAttributeOverrides(overrides: Any) {
311319
attributeOverrides = JSON(overrides)
312320
if gbContext.stickyBucketService != nil {

0 commit comments

Comments
 (0)