This repository has been archived by the owner on Sep 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CollectionView.swift
184 lines (175 loc) · 6.47 KB
/
CollectionView.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
//
// CollectionView.swift
// MongoDBSwift
//
// Created by Andrew Morgan on 23/11/2022.
//
import SwiftUI
import MongoSwift
struct CollectionView: View {
let client: MongoClient
let path: Path
@State private var collection: MongoCollection<BSONDocument>?
@State private var errorMessage = ""
@State private var docs = [BSONDocument]()
@State private var sortField = "_id"
@State private var sortAscending = false
@State private var filterKey = ""
@State private var filterType = "String"
@State private var filterStringValue = ""
@State private var filterIntValue = 0
@State private var filterDoubleValue: Double = 0.0
@State private var filterValue = ""
@State private var docCount: Int = 10
@State private var changeStream: ChangeStream<ChangeStreamEvent<BSONDocument>>?
@State private var latestChangeEvent: ChangeStreamEvent<BSONDocument>?
@State private var showingChangeEvent = false
@State private var enabledChangeStreams = false
@State private var inProgress = false
var body: some View {
VStack {
DataInputsView(
sortField: $sortField,
sortAscending: $sortAscending,
filterKey: $filterKey,
filterType: $filterType,
filterStringValue: $filterStringValue,
filterIntValue: $filterIntValue,
filterDoubleValue: $filterDoubleValue,
docCount: $docCount,
enabledChangeStreams: $enabledChangeStreams,
refreshData: {
Task {
await loadDocs()
}
}
)
.padding()
ZStack {
List(docs, id: \.hashValue) { doc in
if path.dbName == "Single" && path.collectionName == "Collection" {
// This codepath is here to show how the Swift driver can be used with
// MongoDB's single collection pattern. With this pattern, documents with
// different shapes are stored in the same collection - each with a field
// named "type" which indicates what shape the structure should match. The
// pattern is also referred to as "polymorphic collections"
if let docType = doc["docType"] {
switch docType {
case "basket":
BasketView(basket: Basket(doc: doc))
case "item":
ItemView(item: Item(doc: doc))
default:
Text("Unknown doc type")
}
}
} else {
JSONView(doc: doc)
}
}
if inProgress {
ProgressView()
}
}
Spacer()
if !errorMessage.isEmpty {
Text(errorMessage)
.foregroundColor(.red )
}
}
.sheet(isPresented: $showingChangeEvent, content: {
if let latestChangeEvent {
ChangeEventView(event: latestChangeEvent)
}
})
.onChange(of: path, perform: { path in
Task {
filterKey = ""
filterValue = ""
filterType = "String"
sortField = "_id"
sortAscending = false
await loadDocs(path)
await registerChangeStream()
}
})
.onChange(of: enabledChangeStreams, perform: { _ in
Task {
await registerChangeStream()
}
})
.task {
await loadDocs()
await registerChangeStream()
}
}
func loadDocs(_ path: Path? = nil) async {
inProgress = true
docs = [BSONDocument]()
if !errorMessage.isEmpty {
errorMessage = ""
}
let db = client.db(path?.dbName ?? self.path.dbName)
collection = db.collection(path?.collectionName ?? self.path.collectionName)
var bsonFilterValue: BSON?
if !filterKey.isEmpty {
switch filterType {
case "String":
bsonFilterValue = BSON(stringLiteral: filterStringValue)
case "Int":
bsonFilterValue = BSON(integerLiteral: filterIntValue)
case "Float":
bsonFilterValue = BSON(floatLiteral: filterDoubleValue)
default:
print("Unknown filter type")
}
}
var query: BSONDocument = [:]
if let bsonFilterValue {
query = [filterKey: bsonFilterValue]
}
let options = FindOptions(limit: docCount, sort: [sortField: sortAscending ? 1 : -1])
if let collection = collection {
do {
for try await doc in try await collection.find(query, options: options) {
docs.append(doc)
}
} catch {
errorMessage = "Failed to read collection documents: \(error.localizedDescription)"
}
}
inProgress = false
}
func registerChangeStream() async {
// If the view already has an active change stream, close it down
if let changeStream = changeStream {
_ = changeStream.kill()
self.changeStream = nil
}
if enabledChangeStreams {
do {
let changeStreamOptions = ChangeStreamOptions(fullDocument: .updateLookup)
changeStream = try await collection?.watch(options: changeStreamOptions)
_ = changeStream?.forEach({ changeEvent in
withAnimation {
latestChangeEvent = changeEvent
showingChangeEvent = true
Task {
await loadDocs()
}
}
})
} catch {
errorMessage = "Failed to register change stream: \(error.localizedDescription)"
}
}
}
let monoFont = Font
.system(size: 12)
.monospaced()
}
//struct CollectionView_Previews: PreviewProvider {
// static var previews: some View {
// CollectionView()
// }
//}