Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Sources/RxCodable/Maybe+RxCodable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,31 @@ public extension PrimitiveSequenceType where TraitType == MaybeTrait, ElementTyp
}
}

public extension PrimitiveSequenceType where TraitType == MaybeTrait, ElementType == [String: Any] {
public func map<T>(_ type: T.Type, using decoder: JSONDecoder? = nil) -> PrimitiveSequence<TraitType, T> where T: Decodable {
return self
.map { dict in try JSONSerialization.data(withJSONObject: dict) }
.map(type, using: decoder)
}
}

public extension PrimitiveSequenceType where TraitType == MaybeTrait, ElementType: Encodable {
public func toDictionary(_ encoder: JSONEncoder? = nil) -> PrimitiveSequence<TraitType, [String: Any]> {
return self.map { encodable -> [String: Any] in
let data = try (encoder ?? JSONEncoder()).encode(encodable)
let dict = try JSONSerialization.jsonObject(with: data) as? [String: Any]
guard let dictionary = dict else { throw RxError.noElements }
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RxError.noElements should not be used here. It would be better to create a new error type for RxCodable.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm.. It should be

Copy link
Copy Markdown
Author

@iamchiwon iamchiwon Jan 3, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how about this?

enum RxCodableError : Error, CustomDebugStringConvertible {
    case decodeFail
    case encodeFail

    var debugDescription: String {
        switch self {
        case .decodeFail:
            return "Encoding failure"
        case .encodeFail:
            return "Decoding failure"
        } 
    }
}

Copy link
Copy Markdown
Owner

@devxoul devxoul Jan 3, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should give more detailed information. And CustomDebugStringConvertible is not necessary.

enum RxCodableError: Error {
  case castingFailure(Any, Any.Type)
}

You can refer to RxJSONError.

return dictionary
}
}
}

public extension PrimitiveSequenceType where TraitType == MaybeTrait, ElementType: Encodable {
public func toJSONString(_ encoder: JSONEncoder? = nil, encoding: String.Encoding = .utf8) -> PrimitiveSequence<TraitType, String> {
return self.map { encodable -> String in
let data = try (encoder ?? JSONEncoder()).encode(encodable)
let json = String(data: data, encoding: encoding)
return json ?? "{}"
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please don't use default value here.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

got it

}
}
}
30 changes: 30 additions & 0 deletions Sources/RxCodable/ObservableType+RxCodable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,33 @@ public extension ObservableType where E == String {
.map(type, using: decoder)
}
}

public extension ObservableType where E == [String: Any] {
public func map<T>(_ type: T.Type, using decoder: JSONDecoder? = nil) -> Observable<T> where T: Decodable {
return self
.map { dict in try JSONSerialization.data(withJSONObject: dict) }
.map(type, using: decoder)
}
}

public extension ObservableType where E: Encodable {
public func toDictionary(_ encoder: JSONEncoder? = nil) -> Observable<[String: Any]> {
return self.map { encodable -> [String: Any] in
let data = try (encoder ?? JSONEncoder()).encode(encodable)
let dict = try JSONSerialization.jsonObject(with: data) as? [String: Any]
guard let dictionary = dict else { throw RxError.noElements }
return dictionary
}
}
}

public extension ObservableType where E: Encodable {
public func toJSONString(_ encoder: JSONEncoder? = nil, encoding: String.Encoding = .utf8) -> Observable<String> {
return self.map { encodable -> String in
let data = try (encoder ?? JSONEncoder()).encode(encodable)
let json = String(data: data, encoding: encoding)
return json ?? "{}"
}
}
}

29 changes: 29 additions & 0 deletions Sources/RxCodable/Single+RxCodable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,32 @@ public extension PrimitiveSequenceType where TraitType == SingleTrait, ElementTy
.map(type, using: decoder)
}
}

public extension PrimitiveSequenceType where TraitType == SingleTrait, ElementType == [String: Any] {
public func map<T>(_ type: T.Type, using decoder: JSONDecoder? = nil) -> PrimitiveSequence<TraitType, T> where T: Decodable {
return self
.map { dict in try JSONSerialization.data(withJSONObject: dict) }
.map(type, using: decoder)
}
}

public extension PrimitiveSequenceType where TraitType == SingleTrait, ElementType: Encodable {
public func toDictionary(_ encoder: JSONEncoder? = nil) -> PrimitiveSequence<TraitType, [String: Any]> {
return self.map { encodable -> [String: Any] in
let data = try (encoder ?? JSONEncoder()).encode(encodable)
let dict = try JSONSerialization.jsonObject(with: data) as? [String: Any]
guard let dictionary = dict else { throw RxError.noElements }
return dictionary
}
}
}

public extension PrimitiveSequenceType where TraitType == SingleTrait, ElementType: Encodable {
public func toJSONString(_ encoder: JSONEncoder? = nil, encoding: String.Encoding = .utf8) -> PrimitiveSequence<TraitType, String> {
return self.map { encodable -> String in
let data = try (encoder ?? JSONEncoder()).encode(encodable)
let json = String(data: data, encoding: encoding)
return json ?? "{}"
}
}
}
79 changes: 79 additions & 0 deletions Tests/RxCodableTests/RxCodableTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,83 @@ class RxCodableTests: XCTestCase {
XCTAssertEqual(try Single.just(jsonString).map([User].self).toBlocking().first()!, users)
XCTAssertEqual(try Maybe.just(jsonString).map([User].self).toBlocking().first()!, users)
}

func testMapCodableFromDictionary() {
let dictionary:[String:Any] = [
"id": 123,
"name": "iamchiwon",
]
let user = User(id: 123, name: "iamchiwon")
XCTAssertEqual(try Observable.just(dictionary).map(User.self).toBlocking().first()!, user)
XCTAssertEqual(try Single.just(dictionary).map(User.self).toBlocking().first()!, user)
XCTAssertEqual(try Maybe.just(dictionary).map(User.self).toBlocking().first()!, user)
}

func testMapCodableToDictionary() {
let dictionary:[String:Any] = [
"id": 123,
"name": "iamchiwon",
]
let user = User(id: 123, name: "iamchiwon")
XCTAssertEqual(try Observable.just(user).toDictionary().toBlocking().first()! as NSObject, dictionary as NSObject)
XCTAssertEqual(try Single.just(user).toDictionary().toBlocking().first()! as NSObject, dictionary as NSObject)
XCTAssertEqual(try Maybe.just(user).toDictionary().toBlocking().first()! as NSObject, dictionary as NSObject)
}

func testMapCodableToJSONString() {
let jsonString = """
{
"id": 123,
"name": "iamchiwon"
}
"""
let user = User(id: 123, name: "iamchiwon")
XCTAssertEqual(try Observable.just(user).toJSONString().toBlocking().first()!,
try Observable.just(jsonString).map(User.self).toJSONString().toBlocking().first()!)
XCTAssertEqual(try Single.just(user).toJSONString().toBlocking().first()!,
try Single.just(jsonString).map(User.self).toJSONString().toBlocking().first()!)
XCTAssertEqual(try Maybe.just(user).toJSONString().toBlocking().first()!,
try Maybe.just(jsonString).map(User.self).toJSONString().toBlocking().first()!)
}

func testMapCodableArrayToJSONString() {
let jsonString = """
[
{
"id": 123,
"name": "iamchiwon"
},
{
"id": 456,
"name": "devxoul"
}
]
"""
let users = [
User(id: 123, name: "iamchiwon"),
User(id: 456, name: "devxoul"),
]
XCTAssertEqual(try Observable.just(users).toJSONString().toBlocking().first()!,
try Observable.just(jsonString).map([User].self).toJSONString().toBlocking().first()!)
XCTAssertEqual(try Single.just(users).toJSONString().toBlocking().first()!,
try Single.just(jsonString).map([User].self).toJSONString().toBlocking().first()!)
XCTAssertEqual(try Maybe.just(users).toJSONString().toBlocking().first()!,
try Maybe.just(jsonString).map([User].self).toJSONString().toBlocking().first()!)
}

func testMapCodableFromJSONStringToDictionary() {
let jsonString = """
{
"id": 123,
"name": "iamchiwon"
}
"""
let dictionary:[String:Any] = [
"id": 123,
"name": "iamchiwon",
]
XCTAssertEqual(try Observable.just(jsonString).map(User.self).toDictionary().toBlocking().first()! as NSObject, dictionary as NSObject)
XCTAssertEqual(try Single.just(jsonString).map(User.self).toDictionary().toBlocking().first()! as NSObject, dictionary as NSObject)
XCTAssertEqual(try Maybe.just(jsonString).map(User.self).toDictionary().toBlocking().first()! as NSObject, dictionary as NSObject)
}
}