Files
2023-01-14 01:40:25 +03:00

98 lines
3.4 KiB
Swift

//
// DeviceService.swift
//
//
// Created by Juraldinio on 01.08.2022.
//
import Foundation
import Alamofire
public struct DeviceService: NetworkService {
let environment: NetworkEnvironment
let session: Session
public init(environment: NetworkEnvironment) {
self.environment = environment
if let configuration = environment.configuration {
configuration.headers = HTTPHeaders.default
self.session = Session(configuration: configuration)
} else {
self.session = AF
}
}
public func createDevice(uuid: String) async throws -> Device {
let variables = RegisterDeviceRequest.Variables(cid: uuid)
let result = try? await self.session.request(
self.environment.usernames.url,
method: .post,
parameters: RegisterDeviceRequest(variables: variables),
encoder: JSONParameterEncoder.default,
headers: self.environment.usernames.httpHeaders
)
// .responseString { print($0) }
// .cURLDescription { print($0) }
.serializingDecodable(GraphQLResult<RegisterDeviceResponse>.self)
.value
switch result?.result {
case let .firstType(device): return Device(uuid: uuid, id: device.uid, isTrusted: device.isTrustedNow)
case let .secondType(error): throw error.networkServiceError
default: throw NetworkServiceError.uncatched
}
}
public func stateDevice(id: String) async throws -> StateDevice {
let variables = StateDeviceRequest.Variables(uid: id)
let result = try? await self.session.request(
self.environment.usernames.url,
method: .post,
parameters: StateDeviceRequest(variables: variables),
encoder: JSONParameterEncoder.default,
headers: self.environment.usernames.httpHeaders
)
// .responseString { print(">>>>>> \($0)") }
// .cURLDescription { print($0) }
.serializingDecodable(GraphQLResult<StateDeviceResponse>.self)
.value
switch result?.result {
case let .firstType(state): return StateDevice(availableAccounts: state.availableAccounts,
isTrusted: state.isTrustedNow)
case let .secondType(error): throw error.networkServiceError
default: throw NetworkServiceError.uncatched
}
}
public func checkDevice(id: String, token: String) async throws -> DeviceStatus {
let variables = CheckDeviceRequest.Variables(uid: id, token: token)
let result = try? await self.session.request(
self.environment.usernames.url,
method: .post,
parameters: CheckDeviceRequest(variables: variables),
encoder: JSONParameterEncoder.default,
headers: self.environment.usernames.httpHeaders
)
// .responseString { print($0) }
// .cURLDescription { print($0) }
.serializingDecodable(GraphQLResult<CheckDeviceResponse>.self)
.value
switch result?.result {
case let .firstType(status): return status.status
case let .secondType(error): throw error.networkServiceError
default: throw NetworkServiceError.uncatched
}
}
}