Moya+Rx.swift 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // Moya+Rx.swift
  3. // SwiftBilibili
  4. //
  5. // Created by 罗文 on 2021/1/13.
  6. // Copyright © 2021年 罗文. All rights reserved.
  7. //
  8. import Moya
  9. import RxSwift
  10. import SwiftyJSON
  11. import ObjectMapper
  12. extension PrimitiveSequence where Trait == SingleTrait, Element == Moya.Response {
  13. func map<T: ImmutableMappable>(_ type: T.Type) -> PrimitiveSequence<Trait, T> {
  14. return self
  15. .map { (response) -> T in
  16. let json = try JSON(data: response.data)
  17. guard let code = json[RESULT_CODE].int else { throw RequestError.noCodeKey }
  18. if code != StatusCode.success.rawValue { throw RequestError.sysError(statusCode:"\(code)" , errorMsg: json[RESULT_MESSAGE].string) }
  19. if let data = json[RESULT_DATA].dictionaryObject {
  20. return try Mapper<T>().map(JSON: data)
  21. } else if let data = json[RESULT_RESULT].dictionaryObject {
  22. return try Mapper<T>().map(JSON: data)
  23. }
  24. throw RequestError.noDataKey
  25. }.do(onSuccess: { _ in
  26. }, onError: { error in
  27. if error is MapError {
  28. log.error(error)
  29. }
  30. })
  31. }
  32. func map<T: ImmutableMappable>(_ type: T.Type) -> PrimitiveSequence<Trait, [T]> {
  33. return self
  34. .map { response -> [T] in
  35. let json = try JSON(data: response.data)
  36. guard let code = json[RESULT_CODE].int else { throw RequestError.noCodeKey }
  37. if code != StatusCode.success.rawValue { throw RequestError.sysError(statusCode:"\(code)" , errorMsg: json[RESULT_MESSAGE].string) }
  38. var jsonArray: [Any] = []
  39. if let array = json[RESULT_DATA].arrayObject {
  40. jsonArray = array
  41. } else if let array = json[RESULT_RESULT].arrayObject {
  42. jsonArray = array
  43. } else {
  44. throw RequestError.noDataKey
  45. }
  46. guard let data = try? JSONSerialization.data(withJSONObject: jsonArray, options: JSONSerialization.WritingOptions.prettyPrinted),
  47. let jsonString = String(data: data, encoding: String.Encoding.utf8)
  48. else { throw RequestError.wrongData }
  49. return try Mapper<T>().mapArray(JSONString: jsonString)
  50. }.do(onSuccess: { _ in
  51. }, onError: { error in
  52. if error is MapError {
  53. log.error(error)
  54. }
  55. })
  56. }
  57. }