Skip to content

Commit

Permalink
added throws to mock logic instead of fatalError
Browse files Browse the repository at this point in the history
  • Loading branch information
NSCabezon committed Oct 26, 2022
1 parent accc90b commit 1cdadfb
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 30 deletions.
39 changes: 10 additions & 29 deletions Sources/HelpersSPM/Classes/Mock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,21 @@ import Foundation

public typealias JSON = [String: Any]

enum MockError: Error {
case fileNotFound(fileName: String)
}

public class Mock {
public static func loadJSON<T: Decodable>(_ filename: String, as type: T.Type = T.self, inBundle bundle: Bundle = Bundle.main) -> T {
public static func loadJSON<T: Decodable>(_ filename: String, as type: T.Type = T.self, inBundle bundle: Bundle = Bundle.main) throws -> T {
guard let filePath = bundle.path(forResource: filename, ofType: "json") else {
fatalError("Couldn’t find \(filename) in main bundle.")
throw MockError.fileNotFound(fileName: filename)
}

let fileURL = URL(fileURLWithPath: filePath)

return loadJSONAtPath(fileURL, as: T.self)
return try loadJSONAtPath(fileURL, as: T.self)
}

public static func loadJSONAtPath<T: Decodable>(_ filePathURL: URL, as type: T.Type = T.self) -> T {
let data: Data
do {
data = try Data(contentsOf: filePathURL)
} catch {
fatalError("Couldn’t load \(filePathURL.lastPathComponent) from main bundle:\n\(error)")
}

do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn’t parse \(filePathURL.lastPathComponent) as \(T.self):\n\(error)")
}
}
}

public extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
func toJSONString() -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: self, options: []),
let json = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) else {
return nil
}
return json as String
public static func loadJSONAtPath<T: Decodable>(_ filePathURL: URL, as type: T.Type = T.self) throws -> T {
let data = try Data(contentsOf: filePathURL)
return try JSONDecoder().decode(T.self, from: data)
}
}
12 changes: 11 additions & 1 deletion Sources/HelpersSPM/Extensions/DictionaryExtensions.swift
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
import Foundation

extension Dictionary {
public extension Dictionary {
mutating func update(other: Dictionary) {
for (key, value) in other {
self.updateValue(value, forKey: key)
}
}
}

public extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
func toJSONString() -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: self, options: []),
let json = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) else {
return nil
}
return json as String
}
}

0 comments on commit 1cdadfb

Please sign in to comment.