Skip to content

Commit

Permalink
🐛 Persistable 프로토콜을 모든 Repository에서 채택할 수 있도록 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
SwiftyJunnos committed Dec 10, 2023
1 parent f5ac89c commit e8bcdef
Show file tree
Hide file tree
Showing 7 changed files with 118 additions and 137 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ public final class FileManagerStorage: NSObject, MSPersistentStorage {
}
MSLogger.make(category: .fileManager).error("경로의 Data를 성공적으로 가져왔습니다.")

print(dataPath.description)
guard let data = try? Data(contentsOf: dataPath),
let decodedData = try? self.decoder.decode(T.self, from: data) else {
MSLogger.make(category: .fileManager).error("decode에 실패하였습니다.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
public protocol MSPersistentStorage {

func get<T: Codable>(_ type: T.Type, forKey key: String) -> T?
@discardableResult
func set<T: Codable>(value: T, forKey key: String) -> T?

}

This file was deleted.

34 changes: 15 additions & 19 deletions iOS/MSData/Sources/MSData/Repository/JourneyRepository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,17 @@ public struct JourneyRepositoryImplementation: JourneyRepository {
// MARK: - Properties

private let networking: MSNetworking
private let persistent: MSPersistentStorage
public let storage: MSPersistentStorage

@UserDefaultsWrapped(UserDefaultsKey.recordingJourneyID, defaultValue: nil)
private var recordingJourneyID: String?

// MARK: - Properties: Persistable

internal var storage = FileManagerStorage()

// MARK: - Initializer

public init(session: URLSession = URLSession(configuration: .default),
fileManager: FileManager = FileManager()) {
persistentStorage: MSPersistentStorage = FileManagerStorage()) {
self.networking = MSNetworking(session: session)
self.persistent = FileManagerStorage(fileManager: fileManager)
self.storage = persistentStorage
}

// MARK: - Functions
Expand All @@ -62,13 +58,13 @@ public struct JourneyRepositoryImplementation: JourneyRepository {
}

public func fetchRecordingJourney(forID id: String) -> RecordingJourney? {
return self.persistent.get(RecordingJourneyDTO.self, forKey: id)?.toDomain()
return self.storage.get(RecordingJourneyDTO.self, forKey: id)?.toDomain()
}

public func fetchJourneyList(userID: UUID,
minCoordinate: Coordinate,
maxCoordinate: Coordinate) async -> Result<[Journey], Error> {
#if MOCK
#if MOCK
guard let jsonURL = Bundle.module.url(forResource: "MockJourney", withExtension: "json") else {
return .failure((MSNetworkError.invalidRouter))
}
Expand All @@ -83,7 +79,7 @@ public struct JourneyRepositoryImplementation: JourneyRepository {
} catch {
return .failure(error)
}
#else
#else
let router = JourneyRouter.checkJourney(userID: userID,
minCoordinate: CoordinateDTO(minCoordinate),
maxCoordinate: CoordinateDTO(maxCoordinate))
Expand All @@ -94,20 +90,20 @@ public struct JourneyRepositoryImplementation: JourneyRepository {
case .failure(let error):
return .failure(error)
}
#endif
#endif
}

public mutating func startJourney(at coordinate: Coordinate,
userID: UUID) async -> Result<RecordingJourney, Error> {
#if MOCK
#if MOCK
let recordingJourneyID = "657537c178b6463b9f810371"
let recordingJourney = RecordingJourney(id: recordingJourneyID,
startTimestamp: .now,
spots: [],
coordinates: [])
self.recordingJourneyID = recordingJourneyID
return .success(recordingJourney)
#else
#else
let requestDTO = StartJourneyRequestDTO(coordinate: CoordinateDTO(coordinate),
startTimestamp: .now,
userID: userID)
Expand All @@ -124,19 +120,19 @@ public struct JourneyRepositoryImplementation: JourneyRepository {
self.saveToLocal(value: recordingJourney.startTimestamp)

self.recordingJourneyID = recordingJourney.id
#if DEBUG
#if DEBUG
if let recordingJourneyID = self.recordingJourneyID {
MSLogger.make(category: .userDefaults).debug("기록중인 여정 정보가 저장되었습니다: \(recordingJourneyID)")
} else {
MSLogger.make(category: .userDefaults).error("기록중인 여정 정보 저장에 실패했습니다.")
}
#endif
#endif

return .success(recordingJourney)
case .failure(let error):
return .failure(error)
}
#endif
#endif
}

public func recordJourney(journeyID: String,
Expand All @@ -149,9 +145,9 @@ public struct JourneyRepositoryImplementation: JourneyRepository {
case .success(let responseDTO):
let coordinates = responseDTO.coordinates.map { $0.toDomain() }
let recordingJourney = RecordingJourney(id: responseDTO.journeyID,
startTimestamp: Date(),
spots: [],
coordinates: coordinates)
startTimestamp: Date(),
spots: [],
coordinates: coordinates)

responseDTO.coordinates.forEach { self.saveToLocal(value: $0) }

Expand Down
96 changes: 96 additions & 0 deletions iOS/MSData/Sources/MSData/Repository/Persistable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,106 @@
import Foundation

import MSDomain
import MSLogger
import MSPersistentStorage

public protocol Persistable {

var storage: MSPersistentStorage { get }

func saveToLocal(value: Codable)
func loadJourneyFromLocal() -> RecordingJourney?

}

// MARK: - KeyStorage

private struct KeyStorage {

static var id: String?
static var startTimestamp: String?
static var spots = [String]()
static var coordinates = [String]()

}

// MARK: - Default Implementations

extension Persistable {

@discardableResult
public func saveToLocal(value: Codable) -> Bool {
let key = UUID().uuidString
self.storage.set(value: value, forKey: key)

switch value {
case is String:
if KeyStorage.id == nil {
KeyStorage.id = key
} else {
MSLogger.make(category: .persistable).debug("journey ID는 하나의 값만 저장할 수 있습니다.")
return false
}
case is Date:
if KeyStorage.startTimestamp == nil {
KeyStorage.startTimestamp = key
} else {
MSLogger.make(category: .persistable).debug("start tamp는 하나의 값만 저장할 수 있습니다.")
return false
}
case is SpotDTO:
KeyStorage.spots.append(key)
case is CoordinateDTO:
KeyStorage.coordinates.append(key)
default:
MSLogger.make(category: .persistable).debug("RecordingJourney 타입의 요소들만 넣을 수 있습니다.")
return false
}
return true
}

public func loadJourneyFromLocal() -> RecordingJourney? {
guard let id = self.loadID(),
let startTimestamp = self.loadStartTimeStamp() else {
return nil
}
return RecordingJourney(id: id,
startTimestamp: startTimestamp,
spots: self.loadSpots(),
coordinates: self.loadCoordinates())
}

func loadStartTimeStamp() -> Date? {
guard let startTimestampKey = KeyStorage.startTimestamp,
let startTimestamp = self.storage.get(Date.self, forKey: startTimestampKey)
else {
MSLogger.make(category: .persistable).debug("id 또는 startTimestamp가 저장되지 않았습니다.")
return nil
}
return startTimestamp
}

func loadID() -> String? {
guard let idKey = KeyStorage.id,
let id = self.storage.get(String.self, forKey: idKey) else {
MSLogger.make(category: .persistable).debug("id 또는 startTimestamp가 저장되지 않았습니다.")
return nil
}
return id
}

func loadSpots() -> [Spot] {
return KeyStorage.spots.compactMap { spotKey in
let spotDTO = self.storage.get(SpotDTO.self, forKey: spotKey)
return spotDTO?.toDomain()
}
}

func loadCoordinates() -> [Coordinate] {
return KeyStorage.coordinates.compactMap { coordinateKey in
let coordinateDTO = self.storage.get(CoordinateDTO.self, forKey: coordinateKey)
return coordinateDTO?.toDomain()
}
}

}
6 changes: 5 additions & 1 deletion iOS/MSData/Sources/MSData/Repository/SpotRepository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import Foundation
import MSDomain
import MSNetworking
import MSLogger
import MSPersistentStorage

public protocol SpotRepository: Persistable {

Expand All @@ -23,11 +24,14 @@ public struct SpotRepositoryImplementation: SpotRepository {
// MARK: - Properties

private let networking: MSNetworking
public let storage: MSPersistentStorage

// MARK: - Initializer

public init(session: URLSession = URLSession(configuration: .default)) {
public init(session: URLSession = URLSession(configuration: .default),
persistentStorage: MSPersistentStorage = FileManagerStorage()) {
self.networking = MSNetworking(session: session)
self.storage = persistentStorage
}

// MARK: - Functions
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//
// PersistableRepositoryTests.swift
//
// MSData
//
// Created by 전민건 on 12/11/23.
//
Expand Down

0 comments on commit e8bcdef

Please sign in to comment.