summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadREST/ApiHandlers/APIAvailabilityTestRequest.swift
blob: 9f0a9428b1d02ea654dd411d2166624334814899 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//
//  APIAvailabilityTestRequest.swift
//  MullvadREST
//
//  Created by Marco Nikic on 2024-01-08.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import Foundation
import MullvadTypes

extension REST {
    public struct APIAvailabilityTestRequest: Sendable {
        let transport: RESTTransport

        public init(transport: RESTTransport) {
            self.transport = transport
        }

        /// Executes an HTTP `HEAD` request to the "api-addrs" endpoint.
        ///
        /// - Parameter completion: Completes with `nil` if the request was successful, and `Error` otherwise.
        /// - Returns: A cancellable token to cancel the request inflight.
        public func makeRequest(completion: @escaping @Sendable (Swift.Error?) -> Void) -> Cancellable {
            do {
                let factory = RequestFactory(
                    hostname: defaultAPIHostname,
                    pathPrefix: "/app/v1",
                    networkTimeout: defaultAPINetworkTimeout,
                    bodyEncoder: JSONEncoder()
                )
                var request = try factory.createRequest(
                    endpoint: defaultAPIEndpoint,
                    method: .head,
                    pathTemplate: "api-addrs"
                )
                request.urlRequest.cachePolicy = .reloadIgnoringLocalCacheData

                return transport.sendRequest(request.urlRequest) { _, response, error in
                    // Any response in the form of `HTTPURLResponse` means that the API was reached successfully
                    // and implying an HTTP server is running, therefore the test is considered successful.
                    guard response is HTTPURLResponse else {
                        completion(error)
                        return
                    }
                    completion(nil)
                }

            } catch {
                completion(error)
            }
            return AnyCancellable()
        }
    }
}