//
|
// APIMap.swift
|
// OKProject
|
//
|
// Created by alvin_y on 2020/5/28.
|
// Copyright © 2020 yangwang. All rights reserved.
|
//
|
|
import Foundation
|
import RxSwift
|
import Moya
|
import HandyJSON
|
|
extension PrimitiveSequence where Trait == SingleTrait, Element == Response {
|
|
func map<D: HandyJSON>(_ type: D.Type) -> Single<D> {
|
return flatMap { response -> Single<D> in
|
|
guard let model = D.deserialize(from: String(data: response.data, encoding: .utf8)) else {
|
throw MoyaError.underlying(NSError(domain: "com.sdongpo.lvyouyou.error", code: -9999, userInfo: [NSLocalizedDescriptionKey: "数据解析发生错误"]), response)
|
}
|
|
return Single.just(model)
|
}
|
}
|
|
/// 序列化成遵守HandyJSON协议的对象
|
///
|
/// - Parameter type: 需要序列化Data的类型
|
/// - Returns: RxSwift的Signle类型的结果
|
func mapThenValidate<D: HandyJSON>(_ type: D.Type) -> Single<Result<D?, Error>> {
|
|
return flatMap { response -> Single<Result<D?, Error>> in
|
|
do {
|
|
let successfulResponse = try response.filterSuccessfulStatusCodes()
|
if let model = YYModel<D>.self.deserialize(from: String.init(data: successfulResponse.data, encoding: .utf8)){
|
if model.code == 200 || model.code == 0{
|
|
return Single.just(.success(model.data))
|
}
|
else{
|
return Single.just(.failure(YYError.errorDescription(model.msg)))
|
}
|
}else{
|
return Single.just(.failure(YYError.errorDescription("数据解析发生错误")))
|
}
|
|
} catch {
|
|
switch error {
|
case MoyaError.statusCode(_):
|
return Single.just(.failure(YYError.errorDescription("服务器发生未知错误,请稍后再试")))
|
default:
|
return Single.just(.failure(YYError.errorDescription(error.localizedDescription)))
|
}
|
|
}
|
|
}
|
}
|
/// 序列化成遵守HandyJSON协议的对象
|
///
|
/// - Parameter type: 需要序列化Data的类型
|
/// - Returns: RxSwift的Signle类型的结果
|
func mapTravelThenValidate<D: HandyJSON>(_ type: D.Type) -> Single<Result<D?, Error>> {
|
|
return flatMap { response -> Single<Result<D?, Error>> in
|
|
do {
|
|
let successfulResponse = try response.filterSuccessfulStatusCodes()
|
if let model = YYModel<D>.self.deserialize(from: String.init(data: successfulResponse.data, encoding: .utf8)){
|
if model.code == 200 || model.code == 0{
|
return Single.just(.success(model.data))
|
}
|
else{
|
return Single.just(.failure(YYError.errorDescription(model.msg)))
|
}
|
}else{
|
return Single.just(.failure(YYError.errorDescription("数据解析发生错误")))
|
}
|
|
} catch {
|
|
switch error {
|
case MoyaError.statusCode(_):
|
return Single.just(.failure(YYError.errorDescription("服务器发生未知错误,请稍后再试")))
|
default:
|
return Single.just(.failure(YYError.errorDescription(error.localizedDescription)))
|
}
|
|
}
|
|
}
|
}
|
}
|