Skip to content
This repository has been archived by the owner on Sep 30, 2024. It is now read-only.

Commit

Permalink
Merge branch 'deploy/0.1.0' into productive
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeehut committed Feb 14, 2019
2 parents ab19f38 + 9b5c3e6 commit 555aadf
Show file tree
Hide file tree
Showing 27 changed files with 688 additions and 404 deletions.
84 changes: 0 additions & 84 deletions .projlint.yml

This file was deleted.

3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) a

## [Unreleased]
### Added
- None.
- Add `JsonApi` type similar to `TargetType` in Moya with additional JSON `Codable` support.
- Add basic usage documentation based on the Microsoft Translator API.
### Changed
- None.
### Deprecated
Expand Down
File renamed without changes.
170 changes: 170 additions & 0 deletions Frameworks/Microya/Globals/Result.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
// swiftlint:disable all
// Original source: https://raw.githubusercontent.com/apple/swift/swift-5.0-branch/stdlib/public/core/Result.swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

/// A value that represents either a success or a failure, including an
/// associated value in each case.
public enum Result<Success, Failure: Error> {
/// A success, storing a `Success` value.
case success(Success)

/// A failure, storing a `Failure` value.
case failure(Failure)

/// Returns a new result, mapping any success value using the given
/// transformation.
///
/// Use this method when you need to transform the value of a `Result`
/// instance when it represents a success. The following example transforms
/// the integer success value of a result into a string:
///
/// func getNextInteger() -> Result<Int, Error> { /* ... */ }
///
/// let integerResult = getNextInteger()
/// // integerResult == .success(5)
/// let stringResult = integerResult.map({ String($0) })
/// // stringResult == .success("5")
///
/// - Parameter transform: A closure that takes the success value of this
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new success value if this instance represents a success.
public func map<NewSuccess>(
_ transform: (Success) -> NewSuccess
) -> Result<NewSuccess, Failure> {
switch self {
case let .success(success):
return .success(transform(success))
case let .failure(failure):
return .failure(failure)
}
}

/// Returns a new result, mapping any failure value using the given
/// transformation.
///
/// Use this method when you need to transform the value of a `Result`
/// instance when it represents a failure. The following example transforms
/// the error value of a result by wrapping it in a custom `Error` type:
///
/// struct DatedError: Error {
/// var error: Error
/// var date: Date
///
/// init(_ error: Error) {
/// self.error = error
/// self.date = Date()
/// }
/// }
///
/// let result: Result<Int, Error> = // ...
/// // result == .failure(<error value>)
/// let resultWithDatedError = result.mapError({ e in DatedError(e) })
/// // result == .failure(DatedError(error: <error value>, date: <date>))
///
/// - Parameter transform: A closure that takes the failure value of the
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new failure value if this instance represents a failure.
public func mapError<NewFailure>(
_ transform: (Failure) -> NewFailure
) -> Result<Success, NewFailure> {
switch self {
case let .success(success):
return .success(success)
case let .failure(failure):
return .failure(transform(failure))
}
}

/// Returns a new result, mapping any success value using the given
/// transformation and unwrapping the produced result.
///
/// - Parameter transform: A closure that takes the success value of the
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new failure value if this instance represents a failure.
public func flatMap<NewSuccess>(
_ transform: (Success) -> Result<NewSuccess, Failure>
) -> Result<NewSuccess, Failure> {
switch self {
case let .success(success):
return transform(success)
case let .failure(failure):
return .failure(failure)
}
}

/// Returns a new result, mapping any failure value using the given
/// transformation and unwrapping the produced result.
///
/// - Parameter transform: A closure that takes the failure value of the
/// instance.
/// - Returns: A `Result` instance, either from the closure or the previous
/// `.success`.
public func flatMapError<NewFailure>(
_ transform: (Failure) -> Result<Success, NewFailure>
) -> Result<Success, NewFailure> {
switch self {
case let .success(success):
return .success(success)
case let .failure(failure):
return transform(failure)
}
}

/// Returns the success value as a throwing expression.
///
/// Use this method to retrieve the value of this result if it represents a
/// success, or to catch the value if it represents a failure.
///
/// let integerResult: Result<Int, Error> = .success(5)
/// do {
/// let value = try integerResult.get()
/// print("The value is \(value).")
/// } catch error {
/// print("Error retrieving the value: \(error)")
/// }
/// // Prints "The value is 5."
///
/// - Returns: The success value, if the instance represents a success.
/// - Throws: The failure value, if the instance represents a failure.
public func get() throws -> Success {
switch self {
case let .success(success):
return success
case let .failure(failure):
throw failure
}
}
}

//extension Result where Failure == Swift.Error {
// /// Creates a new result by evaluating a throwing closure, capturing the
// /// returned value as a success, or any thrown error as a failure.
// ///
// /// - Parameter body: A throwing closure to evaluate.
// @_transparent
// public init(catching body: () throws -> Success) {
// do {
// self = .success(try body())
// } catch {
// self = .failure(error)
// }
// }
//}

extension Result: Equatable where Success: Equatable, Failure: Equatable { }

extension Result: Hashable where Success: Hashable, Failure: Hashable { }
95 changes: 95 additions & 0 deletions Frameworks/Microya/Models/JsonApi.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//
// Created by Cihat Gündüz on 14.02.19.
// Copyright © 2019 Flinesoft. All rights reserved.
//

// Created by Cihat Gündüz on 14.01.19.

import Foundation

enum JsonApiError: Error {
case noResponseReceived
case noDataReceived
case responseDataConversionFailed(type: String, error: Error)
case unexpectedStatusCode(Int)
case unknownError(Error)
}

protocol JsonApi {
var decoder: JSONDecoder { get }
var encoder: JSONEncoder { get }

var baseUrl: URL { get }
var headers: [String: String] { get }
var path: String { get }
var method: Method { get }
var queryParameters: [(key: String, value: String)] { get }
var bodyData: Data? { get }
}

extension JsonApi {
func request<ResultType: Decodable>(type: ResultType.Type) -> Result<ResultType, JsonApiError> {
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()

var result: Result<ResultType, JsonApiError>?

var request = URLRequest(url: requestUrl())
for (field, value) in headers {
request.setValue(value, forHTTPHeaderField: field)
}

if let bodyData = bodyData {
request.httpBody = bodyData
}

request.httpMethod = method.rawValue

let dataTask = URLSession.shared.dataTask(with: request) { data, urlResponse, error in
result = {
guard error == nil else { return .failure(JsonApiError.unknownError(error!)) }
guard let httpUrlResponse = urlResponse as? HTTPURLResponse else {
return .failure(JsonApiError.noResponseReceived)
}

switch httpUrlResponse.statusCode {
case 200 ..< 300:
guard let data = data else { return .failure(JsonApiError.noDataReceived) }
do {
let typedResult = try self.decoder.decode(type, from: data)
return .success(typedResult)
} catch {
return .failure(JsonApiError.responseDataConversionFailed(type: String(describing: type), error: error))
}

case 400 ..< 500:
return .failure(JsonApiError.unexpectedStatusCode(httpUrlResponse.statusCode))

case 500 ..< 600:
return .failure(JsonApiError.unexpectedStatusCode(httpUrlResponse.statusCode))

default:
return .failure(JsonApiError.unexpectedStatusCode(httpUrlResponse.statusCode))
}
}()

dispatchGroup.leave()
}

dataTask.resume()
dispatchGroup.wait()

return result!
}

private func requestUrl() -> URL {
var urlComponents = URLComponents(url: baseUrl.appendingPathComponent(path), resolvingAgainstBaseURL: false)!

urlComponents.queryItems = []
for (key, value) in queryParameters {
urlComponents.queryItems?.append(URLQueryItem(name: key, value: value))
}

return urlComponents.url!
}
}
14 changes: 14 additions & 0 deletions Frameworks/Microya/Models/Method.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//
// Created by Cihat Gündüz on 14.02.19.
// Copyright © 2019 Flinesoft. All rights reserved.
//

import Foundation

enum Method: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
}
15 changes: 15 additions & 0 deletions Frameworks/SupportingFiles/Microya.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//
// Created by Cihat Gündüz on 27.06.17.
// Copyright © 2017 Flinesoft. All rights reserved.
//

#import <Foundation/Foundation.h>

//! Project version number for Microya.
FOUNDATION_EXPORT double MicroyaVersionNumber;

//! Project version string for Microya.
FOUNDATION_EXPORT const unsigned char MicroyaVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <Microya/PublicHeader.h>

Loading

0 comments on commit 555aadf

Please sign in to comment.