Skip to content
34 changes: 34 additions & 0 deletions Sources/ParseSwift/Operations/ParseOperation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,40 @@ public struct ParseOperation<T>: Savable where T: ParseObject {
self.target = target
}

/**
An operation that sets a field's value.
- Parameters:
- key: The key of the object.
- value: The value to set it to
*/
public func set<W>(_ key: String, value: W) throws -> Self where W: Encodable {
var mutableOperation = self
guard let target = self.target else {
throw ParseError(code: .unknownError, message: "Target shouldn't be nil")
}
let encoded = try target.getEncoder().encode(target, skipKeys: .none)
let jsonObject = try target.getDecoder().decode([String: AnyCodable].self, from: encoded)
let currentValue = jsonObject["score"]
if let currentValue = currentValue?.value as? NSObject,
let updatedValue = value as? NSObject,
currentValue != updatedValue {
mutableOperation.operations[key] = value
}
return mutableOperation
}

/**
An operation that force sets a field's value.
- Parameters:
- key: The key of the object.
- value: The value to set it to
*/
public func forceSet<W>(_ key: String, value: W) throws -> Self where W: Encodable {
var mutableOperation = self
mutableOperation.operations[key] = value
return mutableOperation
}

/**
An operation that increases a numeric field's value by a given amount.
- Parameters:
Expand Down
30 changes: 30 additions & 0 deletions Tests/ParseSwiftTests/ParseOperationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,36 @@ class ParseOperationTests: XCTestCase {
}
#endif

func testSet() throws {
let score = GameScore(score: 10)
let operations = try score.operation.set("score", value: 15)
let expected = "{\"score\":15}"
let encoded = try ParseCoding.parseEncoder()
.encode(operations)
let decoded = try XCTUnwrap(String(data: encoded, encoding: .utf8))
XCTAssertEqual(decoded, expected)
}

func testUnchangedSet() throws {
let score = GameScore(score: 10)
let operations = try score.operation.set("score", value: 10)
let expected = "{}"
let encoded = try ParseCoding.parseEncoder()
.encode(operations)
let decoded = try XCTUnwrap(String(data: encoded, encoding: .utf8))
XCTAssertEqual(decoded, expected)
}

func testForceSet() throws {
let score = GameScore(score: 10)
let operations = try score.operation.forceSet("score", value: 10)
let expected = "{\"score\":10}"
let encoded = try ParseCoding.parseEncoder()
.encode(operations)
let decoded = try XCTUnwrap(String(data: encoded, encoding: .utf8))
XCTAssertEqual(decoded, expected)
}

func testUnset() throws {
let score = GameScore(score: 10)
let operations = score.operation
Expand Down