forked from parse-community/Parse-Swift
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Contents.swift
389 lines (337 loc) · 11.8 KB
/
Contents.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
//: [Previous](@previous)
//: For this page, make sure your build target is set to ParseSwift and targeting
//: `My Mac` or whatever the name of your mac is. Also be sure your `Playground Settings`
//: in the `File Inspector` is `Platform = macOS`. This is because
//: Keychain in iOS Playgrounds behaves differently. Every page in Playgrounds should
//: be set to build for `macOS` unless specified.
import PlaygroundSupport
import Foundation
import ParseSwift
PlaygroundPage.current.needsIndefiniteExecution = true
Task {
do {
try await initializeParse()
} catch {
assertionFailure("Error initializing Parse-Swift: \(error)")
}
}
//: Create your own value typed `ParseObject`.
struct Book: ParseObject, ParseQueryScorable {
//: These are required by ParseObject
var objectId: String?
var createdAt: Date?
var updatedAt: Date?
var ACL: ParseACL?
var score: Double?
var originalData: Data?
//: Your own properties.
var title: String?
var relatedBook: Pointer<Book>?
/*:
Optional - implement your own version of merge
for faster decoding after updating your `ParseObject`.
*/
func merge(with object: Self) throws -> Self {
var updated = try mergeParse(with: object)
if updated.shouldRestoreKey(\.title,
original: object) {
updated.title = object.title
}
if updated.shouldRestoreKey(\.relatedBook,
original: object) {
updated.relatedBook = object.relatedBook
}
return updated
}
}
/*:
It's recommended to place custom initializers in an extension
to preserve the memberwise initializer.
*/
extension Book {
init(title: String) {
self.title = title
}
}
struct Author: ParseObject {
//: These are required by ParseObject.
var objectId: String?
var createdAt: Date?
var updatedAt: Date?
var ACL: ParseACL?
var originalData: Data?
//: Your own properties.
var name: String?
var book: Book?
var otherBooks: [Book]?
/*:
Optional - implement your own version of merge
for faster decoding after updating your `ParseObject`.
*/
func merge(with object: Self) throws -> Self {
var updated = try mergeParse(with: object)
if updated.shouldRestoreKey(\.name,
original: object) {
updated.name = object.name
}
if updated.shouldRestoreKey(\.book,
original: object) {
updated.book = object.book
}
if updated.shouldRestoreKey(\.otherBooks,
original: object) {
updated.otherBooks = object.otherBooks
}
return updated
}
}
/*:
It's recommended to place custom initializers in an extension
to preserve the memberwise initializer.
*/
extension Author {
init(name: String, book: Book) {
self.name = name
self.book = book
}
}
var newBook = Book(title: "hello")
let author = Author(name: "Alice", book: newBook)
author.save { result in
switch result {
case .success(let savedAuthorAndBook):
assert(savedAuthorAndBook.objectId != nil)
assert(savedAuthorAndBook.createdAt != nil)
assert(savedAuthorAndBook.updatedAt != nil)
print("Saved: \(savedAuthorAndBook)")
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
//: Pointer array.
let otherBook1 = Book(title: "I like this book")
let otherBook2 = Book(title: "I like this book also")
var author2 = Author(name: "Bruce", book: newBook)
author2.otherBooks = [otherBook1, otherBook2]
author2.save { result in
switch result {
case .success(let savedAuthorAndBook):
assert(savedAuthorAndBook.objectId != nil)
assert(savedAuthorAndBook.createdAt != nil)
assert(savedAuthorAndBook.updatedAt != nil)
assert(savedAuthorAndBook.otherBooks?.count == 2)
/*:
Notice the pointer objects have not been updated on the
client.If you want the latest pointer objects, fetch and include them.
*/
print("Saved: \(savedAuthorAndBook)")
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
//: Query for your new saved author
let query1 = Author.query("name" == "Bruce")
query1.first { results in
switch results {
case .success(let author):
print("Found author: \(author)")
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
/*:
You will notice in the query above, the fields `book` and `otherBooks` only contain
arrays consisting of key/value pairs of `objectId`. These are called Pointers
in `Parse`.
If you want to retrieve the complete object pointed to in `book`, you need to add
the field names containing the objects specifically in `include` in your query.
*/
/*:
Here, we include `book`. If you wanted `book` and `otherBook`, you
could have used: `.include(["book", "otherBook"])`.
*/
let query2 = Author.query("name" == "Bruce")
.include("book")
query2.first { results in
switch results {
case .success(let author):
//: Save the book to use later
if let book = author.book {
newBook = book
}
print("Found author and included \"book\": \(author)")
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
/*:
When you have many fields that are pointing to objects, it may become tedious
to add all of them to the list. You can quickly retreive all pointer objects by
using `includeAll`. You can also use `include("*")` to retrieve all pointer
objects.
*/
let query3 = Author.query("name" == "Bruce")
.includeAll()
query3.first { results in
switch results {
case .success(let author):
print("Found author and included all: \(author)")
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
//: You can also check if a field is equal to a ParseObject.
do {
let query4 = try Author.query("book" == newBook)
.includeAll()
query4.first { results in
switch results {
case .success(let author):
print("Found author and included all: \(author)")
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
} catch {
print("\(error)")
}
//: Here's an example of saving Pointers as properties.
do {
//: First we query
let query5 = try Author.query("book" == newBook)
.include("book")
query5.first { results in
switch results {
case .success(let author):
print("Found author and included \"book\": \(author)")
/*:
Setup related books. Using `.mergeable` or `set()`
allows you to only send the updated keys to the
parse server as opposed to the whole object.
*/
var modifiedNewBook = newBook.mergeable
modifiedNewBook.relatedBook = try? author.otherBooks?.first?.toPointer()
modifiedNewBook.save { result in
switch result {
case .success(let updatedBook):
assert(updatedBook.objectId != nil)
assert(updatedBook.createdAt != nil)
assert(updatedBook.updatedAt != nil)
assert(updatedBook.relatedBook != nil)
print("Saved: \(updatedBook)")
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
} catch {
print("\(error)")
}
//: Here's an example of querying using matchesText.
do {
let query6 = try Book.query(matchesText(key: "title",
text: "like",
options: [:]))
.include(["*"])
.sortByTextScore()
query6.find { results in
switch results {
case .success(let books):
print("Found books and included all: \(books)")
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
} catch {
print("\(error)")
}
//: Batching saves with saved and unsaved pointer items.
var author3 = Author(name: "Logan", book: newBook)
let otherBook3 = Book(title: "I like this book")
let otherBook4 = Book(title: "I like this book also")
author3.otherBooks = [otherBook3, otherBook4]
[author3].saveAll { result in
switch result {
case .success(let savedAuthorsAndBook):
savedAuthorsAndBook.forEach { eachResult in
switch eachResult {
case .success(let savedAuthorAndBook):
assert(savedAuthorAndBook.objectId != nil)
assert(savedAuthorAndBook.createdAt != nil)
assert(savedAuthorAndBook.updatedAt != nil)
assert(savedAuthorAndBook.otherBooks?.count == 2)
/*:
Notice the pointer objects have not been updated on the
client.If you want the latest pointer objects, fetch and include them.
*/
print("Saved \(savedAuthorAndBook)")
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
//: Batching saves with unsaved pointer items.
var newBook2 = Book(title: "world")
var author4 = Author(name: "Scott", book: newBook2)
author4.otherBooks = [otherBook3, otherBook4]
[author4].saveAll { result in
switch result {
case .success(let savedAuthorsAndBook):
savedAuthorsAndBook.forEach { eachResult in
switch eachResult {
case .success(let savedAuthorAndBook):
assert(savedAuthorAndBook.objectId != nil)
assert(savedAuthorAndBook.createdAt != nil)
assert(savedAuthorAndBook.updatedAt != nil)
assert(savedAuthorAndBook.otherBooks?.count == 2)
author4 = savedAuthorAndBook
/*:
Notice the pointer objects have not been updated on the
client.If you want the latest pointer objects, fetch and include them.
*/
print("Saved: \(savedAuthorAndBook)")
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
//: Batching saves by updating an already saved object.
author4.fetch { result in
switch result {
case .success(var fetchedAuthor):
print("The latest author: \(fetchedAuthor)")
fetchedAuthor.name = "R.L. Stine"
[fetchedAuthor].saveAll { result in
switch result {
case .success(let savedAuthorsAndBook):
savedAuthorsAndBook.forEach { eachResult in
switch eachResult {
case .success(let savedAuthorAndBook):
assert(savedAuthorAndBook.objectId != nil)
assert(savedAuthorAndBook.createdAt != nil)
assert(savedAuthorAndBook.updatedAt != nil)
assert(savedAuthorAndBook.otherBooks?.count == 2)
print("Updated: \(savedAuthorAndBook)")
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
case .failure(let error):
assertionFailure("Error fetching: \(error)")
}
}
PlaygroundPage.current.finishExecution()
//: [Next](@next)