~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
59 lines · 1.9 KB Raw History
import Foundation
import XCTest

@testable import OldFella

final class RefreshRaceURLProtocol: URLProtocol {
    static var handler: ((URLRequest) throws -> (Int, Data))?
    private static let lock = NSLock()
    private static var requests: [URLRequest] = []

    static var recordedRequests: [URLRequest] {
        lock.lock()
        defer { lock.unlock() }
        return requests
    }

    static func clearRequests() {
        lock.lock()
        requests = []
        lock.unlock()
    }

    override static func canInit(with request: URLRequest) -> Bool { true }
    override static func canonicalRequest(for request: URLRequest) -> URLRequest { request }

    override func startLoading() {
        Self.lock.lock()
        Self.requests.append(request)
        let handler = Self.handler
        Self.lock.unlock()
        guard let handler, let url = request.url else {
            client?.urlProtocol(self, didFailWithError: ServiceError.invalidResponse)
            return
        }
        let request = self.request
        DispatchQueue.global().async {
            let result: (Int, Data)
            do {
                result = try handler(request)
            } catch {
                self.client?.urlProtocol(self, didFailWithError: error)
                return
            }
            guard
                let response = HTTPURLResponse(
                    url: url, statusCode: result.0, httpVersion: "HTTP/1.1",
                    headerFields: ["Content-Type": "application/json"])
            else {
                self.client?.urlProtocol(self, didFailWithError: ServiceError.invalidResponse)
                return
            }
            self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
            self.client?.urlProtocol(self, didLoad: result.1)
            self.client?.urlProtocolDidFinishLoading(self)
        }
    }

    override func stopLoading() {}
}