-
Notifications
You must be signed in to change notification settings - Fork 0
/
GlossJSONStorage.swift
71 lines (54 loc) · 1.9 KB
/
GlossJSONStorage.swift
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//
// JSONStorage.swift
// Created by Piotr Bernad on 04.04.2017.
//
import Foundation
import Gloss
public enum JSONStorageType {
case documents
case cache
var searchPathDirectory: FileManager.SearchPathDirectory {
switch self {
case .documents:
return .documentDirectory
case .cache:
return .cachesDirectory
}
}
}
public enum JSONStorageError: Error {
case wrongDocumentPath
case couldNotCreateJSON
}
public class JSONStorage<T: Glossy> {
private let document: String
private let type: JSONStorageType
private lazy var storeUrl: URL? = {
guard let dir = FileManager.default.urls(for: self.type.searchPathDirectory, in: .userDomainMask).first else {
assertionFailure("could not find storage path")
return nil
}
return dir.appendingPathComponent(self.document)
}()
public init(type: JSONStorageType, document: String) {
self.type = type
self.document = document
}
public func read() throws -> [T] {
guard let storeUrl = storeUrl else {
throw JSONStorageError.wrongDocumentPath
}
let readData = try Data(contentsOf: storeUrl)
let json = try JSONSerialization.jsonObject(with: readData, options: .allowFragments)
guard let jsonArray = json as? [Gloss.JSON] else { return [] }
return Array<T>.from(jsonArray: jsonArray) ?? []
}
public func write(_ itemsToWrite: [T]) throws {
let json = itemsToWrite.map{$0.toJSON()}
let jsonData = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
guard let storeUrl = storeUrl else {
throw JSONStorageError.wrongDocumentPath
}
try jsonData.write(to: storeUrl)
}
}