forked from parse-community/Parse-Swift
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathContents.swift
191 lines (163 loc) · 5.75 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
//: [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 `ParseCloudable` type.
struct Hello: ParseCloudable {
//: Return type of your Cloud Function
typealias ReturnType = String
//: These are required by `ParseCloudable`, you can set the default value to make it easier
//: to use.
var functionJobName: String = "hello"
}
//: Create another `ParseCloudable` type.
struct TestCloudCode: ParseCloudable {
//: Return type of your Cloud Function
typealias ReturnType = [String: Int]
//: These are required by `ParseCloudable`, you can set the default value to make it easier
//: to use.
var functionJobName: String = "testCloudCode"
//: If your cloud function takes arguments, they can be passed by creating properties:
var argument1: [String: Int]
}
//: Create another `ParseCloudable` type.
struct TestCloudCodeError: ParseCloudable {
//: Return type of your Cloud Function
typealias ReturnType = String
//: These are required by `ParseCloudable`, you can set the default value to make it easier
//: to use.
var functionJobName: String = "testCloudCodeError"
}
/*: Assuming you have the Cloud Function named "hello" on your parse-server:
// main.js
Parse.Cloud.define('hello', async (request) => {
console.log('From client: ' + JSON.stringify(request));
return 'Hello world!';
});
*/
let hello = Hello()
hello.runFunction { result in
switch result {
case .success(let response):
print("Response from cloud function: \(response)")
case .failure(let error):
assertionFailure("Error calling cloud function: \(error)")
}
}
/*: Assuming you have the Cloud Function named "testCloudCode" on your parse-server.
You can catch custom errors created in Cloud Code:
// main.js
Parse.Cloud.define("testCloudCode", async(request) => {
console.log('From client: ' + JSON.stringify(request));
return request.params.argument1;
});
*/
let testCloudCode = TestCloudCode(argument1: ["test": 5])
testCloudCode.runFunction { result in
switch result {
case .success(let response):
print("Response from cloud function: \(response)")
case .failure(let error):
assertionFailure("Error: \(error.localizedDescription)")
}
}
/*: Assuming you have the Cloud Function named "testCloudCode" on your parse-server.
You can catch custom errors created in Cloud Code:
// main.js
Parse.Cloud.define("testCloudCodeError", async(request) => {
console.log('From client: ' + JSON.stringify(request));
throw new Parse.Error(3000, "cloud has an error on purpose.");
});
*/
let testCloudCodeError = TestCloudCodeError()
testCloudCodeError.runFunction { result in
switch result {
case .success:
assertionFailure("Should have thrown a custom error")
case .failure(let error):
switch error.code {
case .other:
guard let otherCode = error.otherCode else {
assertionFailure("Should have unwrapped otherCode")
return
}
switch otherCode {
case 3000:
print("Received Cloud Code error: \(error)")
default:
assertionFailure("""
Should have received code \"3000\"
Instead received \(error)
""")
}
default:
assertionFailure("""
Should have received code \"other\"
Instead received \(error)
""")
}
}
}
//: Jobs can be run the same way by using the method `startJob()`.
/*: Saving objects with context for beforeSave, afterSave, etc.
Parse.Cloud.beforeSave("GameScore", async(request) => {
console.log('From client context: ' + JSON.stringify(request.context));
});
*/
//: Create your own value typed `ParseObject`.
struct GameScore: 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 points: Int?
/*:
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(\.points,
original: object) {
updated.points = object.points
}
return updated
}
}
//: It's recommended to place custom initializers in an extension
//: to preserve the memberwise initializer.
extension GameScore {
//: Custom initializer.
init(points: Int) {
self.points = points
}
}
//: Define a GameScore.
let score = GameScore(points: 10)
//: Save asynchronously with completion block with the context option.
score.save(options: [.context(["hello": "world"])]) { result in
switch result {
case .success(let savedScore):
print("Successfully saved \(savedScore)")
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
PlaygroundPage.current.finishExecution()
//: [Next](@next)