Search
Duplicate

API Manager 구현하기

Created
2024/02/16 14:32
Tags
태그

API Manager 구현하기

// // RsvpManager.swift // glimpese-iOS // // Created by KIM Hyung Jun on 4/2/24. // import ComposableArchitecture import Foundation import Moya @DependencyClient struct RsvpManager { var addParticipant: @Sendable (_ eventId: Int, _ interests: [String], _ purpose: String) async throws -> RsvpResponse } extension RsvpManager: DependencyKey { static let liveValue = Self( addParticipant: { eventId, interests, purpose in let provider = MoyaProvider<RsvpAPI>(plugins: [MoyaLoggingPlugin()]) return try await withCheckedThrowingContinuation { continuation in provider.request(.addParticipant(eventId: eventId, interests: interests, purpose: purpose)) { result in switch result { case let .success(response): do { print("성공") let rsvpResponse = try JSONDecoder().decode(RsvpResponse.self, from: response.data) continuation.resume(returning: rsvpResponse) } catch { continuation.resume(throwing: error) } case let .failure(error): print("실패") continuation.resume(throwing: error) } } } } ) } extension DependencyValues { var rsvpManager: RsvpManager { get { self[RsvpManager.self] } set { self[RsvpManager.self] = newValue } } }
Swift
복사

 @DependencyClient 및 Dependency 프로토콜

@DependencyClientDependencyKey 는 TCA에서 의존성 주입을 위해 사용되는 개념이다.
@DependencyClient 속성 래퍼를 사용하여 RsvpManager에 필요한 의존성을 선언한다.
DependencyKey 프로토콜을 구현하여 실제 환경에서 사용될 기본값(liveValue)을 제공한다.

 RsvpManager 구조체

RsvpManager 는 이벤트 참가자를 추가하는 addParticipant 함수를 포함한다.
이 함수는 비동기 함수이며, Swift의 동시성 모델을 사용하여 네트워크 요청을 처리한다.

addParticipant 메서드

이 메서드는 이벤트 ID, 관심사 목록, 목적을 입력 받는다.
그리고 RsvpResponse 타입의 결과를 비동기적으로 반환한다. 내부적으로는 MoyaProvider를 사용하여 RsvpAPI.addParticipant 엔트포인트에 대한 POST 요청을 수행한다.

 withCheckedThrowingContinuation

이 메서드를 사용하여 비동기 네트워크 요청을 처리한다.
MoyaProvider의 요청이 완료되면, 요청의 성공 또는 실패 결과에 따라 continuation을 resume하여 비동기 작업을 완료한다.

 DependencyValues 확장

DependencyValues 에 rsvpManager 프로퍼티를 추가하여, 앱 전체에서 RsvpManager 인스턴스에 접근할 수 있도록 한다.
이를통해, 의존성 주입을 통해 RsvpManager의 다른 구현을 쉽게 교체할 수 있다.