← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Shared/Persistence/EntityMapping.swift (6479B)

1import CoreData
2import Foundation
3
4/// Conversions between the value types in `Models/` and their Core Data
5/// entities. Encoded fields (`options`, `context`, `place`, `value`) are JSON.
6enum ModelCoding {
7    static func encode<T: Encodable>(_ value: T) throws -> Data {
8        let encoder = JSONEncoder()
9        encoder.outputFormatting = .sortedKeys
10        return try encoder.encode(value)
11    }
12
13    static func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T {
14        try JSONDecoder().decode(type, from: data)
15    }
16}
17
18enum EntityMappingError: Error, Equatable {
19    case missingField(entity: String, field: String)
20    case unknownValue(entity: String, field: String, value: String)
21}
22
23extension QuestionEntity {
24    func update(from question: Question) throws {
25        id = question.id
26        prompt = question.prompt
27        kind = question.kind.rawValue
28        options = question.options.isEmpty ? nil : try ModelCoding.encode(question.options)
29        placeholder = question.placeholder
30        narrativeRule = try question.narrativeRule.map { try ModelCoding.encode($0) }
31        askOn = question.askOn.rawValue
32        order = Int32(question.order)
33        showsInTimeline = question.showsInTimeline
34        archivedAt = question.archivedAt
35        modifiedAt = question.modifiedAt
36    }
37
38    func question() throws -> Question {
39        guard let id, let prompt, let modifiedAt else {
40            throw EntityMappingError.missingField(entity: "Question", field: "id/prompt/modifiedAt")
41        }
42        guard let kind = kind.flatMap(QuestionKind.init(rawValue:)) else {
43            throw EntityMappingError.unknownValue(
44                entity: "Question", field: "kind", value: self.kind ?? "nil")
45        }
46        return Question(
47            id: id,
48            prompt: prompt,
49            kind: kind,
50            options: try options.map { try ModelCoding.decode([String].self, from: $0) } ?? [],
51            placeholder: placeholder,
52            narrativeRule: try narrativeRule.map { try ModelCoding.decode(NarrativeRule.self, from: $0) },
53            askOn: SurveyKinds(rawValue: askOn),
54            order: Int(order),
55            showsInTimeline: showsInTimeline,
56            archivedAt: archivedAt,
57            modifiedAt: modifiedAt
58        )
59    }
60}
61
62extension TokenEntity {
63    func update(from token: Token) throws {
64        id = token.id
65        questionID = token.questionID
66        text = token.text
67        place = try token.place.map { try ModelCoding.encode($0) }
68        narrativeForm = token.narrativeForm
69        mergedInto = token.mergedInto
70        archivedAt = token.archivedAt
71        modifiedAt = token.modifiedAt
72    }
73
74    func token() throws -> Token {
75        guard let id, let questionID, let text, let modifiedAt else {
76            throw EntityMappingError.missingField(
77                entity: "Token", field: "id/questionID/text/modifiedAt")
78        }
79        return Token(
80            id: id,
81            questionID: questionID,
82            text: text,
83            place: try place.map { try ModelCoding.decode(PlaceDetails.self, from: $0) },
84            narrativeForm: narrativeForm,
85            mergedInto: mergedInto,
86            archivedAt: archivedAt,
87            modifiedAt: modifiedAt
88        )
89    }
90}
91
92extension ReportEntity {
93    /// Copies `report` into the entity, replacing any existing responses.
94    func update(from report: Report) throws {
95        guard let context = managedObjectContext else {
96            preconditionFailure("ReportEntity must be inserted before updating")
97        }
98        id = report.id
99        date = report.date
100        timeZone = report.timeZone
101        kind = report.kind.rawValue
102        trigger = report.trigger.rawValue
103        state = report.state.rawValue
104        promptedAt = report.promptedAt
105        completedAt = report.completedAt
106        self.context = try ModelCoding.encode(report.context)
107        modifiedAt = report.modifiedAt
108
109        for case let existing as ResponseEntity in responses ?? [] {
110            context.delete(existing)
111        }
112        for (index, response) in report.responses.enumerated() {
113            let entity = ResponseEntity(context: context)
114            entity.order = Int16(index)
115            entity.questionID = response.questionID
116            entity.prompt = response.prompt
117            entity.value = try response.value.map { try ModelCoding.encode($0) }
118            entity.report = self
119        }
120    }
121
122    func report() throws -> Report {
123        guard let id, let date, let timeZone, let modifiedAt else {
124            throw EntityMappingError.missingField(
125                entity: "Report",
126                field: "id/date/timeZone/modifiedAt"
127            )
128        }
129        guard let kind = kind.flatMap(ReportKind.init(rawValue:)) else {
130            throw EntityMappingError.unknownValue(
131                entity: "Report", field: "kind", value: self.kind ?? "nil")
132        }
133        guard let trigger = trigger.flatMap(ReportTrigger.init(rawValue:)) else {
134            throw EntityMappingError.unknownValue(
135                entity: "Report",
136                field: "trigger",
137                value: self.trigger ?? "nil"
138            )
139        }
140        guard let state = state.flatMap(ReportState.init(rawValue:)) else {
141            throw EntityMappingError.unknownValue(
142                entity: "Report", field: "state", value: self.state ?? "nil")
143        }
144        let responseEntities = (responses as? Set<ResponseEntity> ?? []).sorted {
145            $0.order < $1.order
146        }
147        return Report(
148            id: id,
149            date: date,
150            timeZone: timeZone,
151            kind: kind,
152            trigger: trigger,
153            state: state,
154            promptedAt: promptedAt,
155            completedAt: completedAt,
156            context: try self.context.map { try ModelCoding.decode(Context.self, from: $0) }
157                ?? Context(),
158            responses: try responseEntities.map { try $0.response() },
159            modifiedAt: modifiedAt
160        )
161    }
162}
163
164extension ResponseEntity {
165    func response() throws -> Response {
166        guard let questionID, let prompt else {
167            throw EntityMappingError.missingField(entity: "Response", field: "questionID/prompt")
168        }
169        return Response(
170            questionID: questionID,
171            prompt: prompt,
172            value: try value.map { try ModelCoding.decode(ResponseValue.self, from: $0) }
173        )
174    }
175}