1
0
mirror of https://github.com/metabolist/metatext synced 2024-12-21 07:26:08 +01:00
metatext-app-ios-iphone-ipad/HTTP/Sources/Stubbing/StubbingURLProtocol.swift

61 lines
1.7 KiB
Swift
Raw Normal View History

// Copyright © 2020 Metabolist. All rights reserved.
import Foundation
2020-08-31 03:40:58 +02:00
import HTTP
2020-08-31 12:21:01 +02:00
public class StubbingURLProtocol: URLProtocol {
2020-08-31 03:40:58 +02:00
private static var targetsForURLs = [URL: Target]()
2020-08-31 12:21:01 +02:00
override public class func canInit(with task: URLSessionTask) -> Bool {
true
}
2020-08-31 12:21:01 +02:00
override public class func canInit(with request: URLRequest) -> Bool {
true
}
2020-08-31 12:21:01 +02:00
override public class func canonicalRequest(for request: URLRequest) -> URLRequest {
request
}
2020-08-31 12:21:01 +02:00
override public func startLoading() {
guard
let url = request.url,
2020-08-31 12:21:01 +02:00
let stub = Self.stub(request: request, target: Self.targetsForURLs[url]) else {
preconditionFailure("Stub for request not found")
}
switch stub {
case let .success((response, data)):
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowed)
client?.urlProtocol(self, didLoad: data)
client?.urlProtocolDidFinishLoading(self)
case let .failure(error):
client?.urlProtocol(self, didFailWithError: error)
}
}
2020-08-31 12:21:01 +02:00
override public func stopLoading() {}
}
private extension StubbingURLProtocol {
class func stub(
request: URLRequest,
target: Target? = nil,
userInfo: [String: Any] = [:]) -> HTTPStub? {
guard let url = request.url else {
return nil
}
return (target as? Stubbing)?.stub(url: url)
}
}
2020-08-31 03:40:58 +02:00
extension StubbingURLProtocol: TargetProcessing {
2020-08-31 12:21:01 +02:00
public static func process(target: Target) {
2020-08-31 03:40:58 +02:00
if let url = try? target.asURLRequest().url {
targetsForURLs[url] = target
}
}
}