Giter Site home page Giter Site logo

gperdomor / moyaobjectmapper Goto Github PK

View Code? Open in Web Editor NEW
11.0 3.0 2.0 87 KB

ObjectMapper bindings for Moya, RxSwift and ReactiveSwift

License: MIT License

Swift 91.64% Ruby 6.96% Shell 1.40%
swift rxswift reactiveswift moya mapper swift3 objectmapper json

moyaobjectmapper's Introduction

MoyaObjectMapper

Build Status codecov Carthage compatible CocoaPods compatible Swift Package Manager compatible

ObjectMapper bindings for Moya for easier JSON serialization. Includes RxSwift and ReactiveSwift bindings as well.

Installation

CocoaPods

Use the following entry in your Podfile

pod 'MoyaObjectMapper', '1.0.3'

The subspec if you want to use the bindings over RxSwift.

pod 'MoyaObjectMapper/RxSwift', '1.0.3'

And the subspec if you want to use the bindings over ReactiveSwift.

pod 'MoyaObjectMapper/ReactiveSwift', '1.0.3'

Usage

Create a model struct or class. It needs to implement protocol Mappable. More details about model creation here

import Foundation
import ObjectMapper

struct Repository: Mappable {
    var identifier: Int!
    var name: String!
    var fullName: String!
    var language: String?
    
    init?(map: Map) {
        if map.JSON["id"] == nil {
            return nil
        }
    }
    
    mutating func mapping(map: Map) {
        identifier <- map["id"]
        name <- map["name"]
        fullName <- map["full_name"]
        language <- map["language"]
    }
}

Then you have methods that extends the response from Moya. These methods are:

map(to: type, context: MapContext? = nil) // map object
map(to: [type], context: MapContext? = nil) // map array of objects

For RxSwift and ReactiveCocoa additionally methods for optional mapping are provided. These methods are:

mapOptional(to: type, context: MapContext? = nil)
mapOptional(to: [type], context: MapContext? = nil)

See examples below, or in a Demo project.

1. Normal usage (without RxSwift or ReactiveCocoa)

provider = MoyaProvider<GitHub>()
provider.request(GitHub.repos(username: "gperdomor")) { (result) in
    if case .success(let response) = result {
        do {
            let repos = try response.map(to: [Repository.self])
            print(repos)
        } catch Error.jsonMapping(let error) {
            print(try? error.mapString())
        } catch {
            print(":(")
        }
    }
}

2. RxSwift

provider = RxMoyaProvider<GitHub>()
provider.request(GitHub.repo(fullName: "gperdomor/sygnaler"))
        .map(to: Repository.self)
        .subscribe { event in
            switch event {
            case .next(let repo):
                print(repo)
            case .error(let error):
                print(error)
            default: break
            }
        }

Additionally, modules for RxSwift contains optional mappings. It basically means that if the mapping fails, mapper doesn't throw errors but returns nil. For instance:

provider = RxMoyaProvider<GitHub>()
provider
    .request(GitHub.repos(username: "gperdomor"))
    .mapOptional(to: [Repository.self])
    .subscribe { event in
        switch event {
        case .next(let repos):
            // Here we can have either nil or [Repository] object.
            print(repos)
        case .error(let error):
            print(error)
        default: break
        }
    }

3. ReactiveSwift

provider = ReactiveSwiftMoyaProvider<GitHub>()
provider
    .request(GitHub.repos(username: "gperdomor"))
    .map(to: [Repository.self])
    .start { event in
        switch event {
        case .value(let repos):
            print(repos)
        case .failed(let error):
            print(error)
        default: break
        }
    }

Additionally, modules for ReactiveSwift contains optional mappings. It basically means that if the mapping fails, mapper doesn't throw errors but returns nil. For instance:

provider = ReactiveSwiftMoyaProvider<GitHub>()
provider
    .request(GitHub.repos(username: "gperdomor"))
    .mapOptional(to: [Repository.self])
    .start { event in
        switch event {
        case .value(let repos):
            // Here we can have either nil or [Repository] object.
            print(repos)
        case .failed(let error):
            print(error)
        default: break
        }
    }

Sample Project

There's a sample project in the Demo directory. To use it, run pod install to download the required libraries. Have fun!

Other Mappers

Contributing

Hey! Like MoyaObjectMapper? Awesome! We could actually really use your help!

Open source isn't just writing code. MoyaObjectMapper could use your help with any of the following:

  • Finding (and reporting!) bugs.
  • New feature suggestions.
  • Answering questions on issues.
  • Documentation improvements.
  • Reviewing pull requests.
  • Helping to manage issue priorities.
  • Fixing bugs/new features.

If any of that sounds cool to you, send a pull request! After a few contributions, we'll add you as an admin to the repo so you can merge pull requests and help steer the ship ๐Ÿšข

License

MoyaObjectMapper is available under the MIT license. See the LICENSE file for more info.

moyaobjectmapper's People

Contributors

gperdomor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

moyaobjectmapper's Issues

KeyPath support for response

Thanks for nice mapper. Will it be possible to add key path support for response ? I have Issue response coming from server which is not on the root. They are inside the root element like

{
  "issues":[{id:1},{id:2}] 
  "success": 1
}

so function would be like

    internal func findIssues(repository: Repository) -> Observable<[Issue]?> {
        return self.provider
            .request(GitHub.issues(repositoryFullName: repository.fullName))
            .debug()
            .mapOptional(to: [Issue.self], fromKey:"issues")
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.