-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocalFirebaseRESTSupport.swift
More file actions
358 lines (312 loc) · 11.4 KB
/
Copy pathLocalFirebaseRESTSupport.swift
File metadata and controls
358 lines (312 loc) · 11.4 KB
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
//
// LocalFirebaseRESTSupport.swift
// DevLogAppTests
//
// Created by opfic on 4/6/26.
//
import Foundation
final class LocalFirebaseRESTSupport {
struct AuthSession {
let userId: String
let idToken: String
}
struct SeededWebPage {
let documentId: String
let urlString: String
}
static let shared = LocalFirebaseRESTSupport()
private let authBaseURL = URL(string: "http://127.0.0.1:9298")!
private let firestoreBaseURL = URL(string: "http://127.0.0.1:8280")!
private let functionsBaseURL = URL(string: "http://127.0.0.1:5201")!
private init() { }
func anonymousSignIn() async throws -> AuthSession {
let googleServiceInfo = try loadGoogleServiceInfo()
var request = URLRequest(
url: authBaseURL.appending(
path: "identitytoolkit.googleapis.com/v1/accounts:signUp",
directoryHint: .notDirectory
).appending(queryItems: [
URLQueryItem(name: "key", value: googleServiceInfo.apiKey)
])
)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONSerialization.data(
withJSONObject: ["returnSecureToken": true]
)
let payload = try await sendJSON(request)
guard
let userId = payload["localId"] as? String,
let idToken = payload["idToken"] as? String
else {
throw RESTError.invalidResponse
}
return AuthSession(
userId: userId,
idToken: idToken
)
}
func seedPushNotification(
userId: String,
notificationId: String = UUID().uuidString
) async throws -> String {
let fields = [
"title": stringValue("테스트 알림"),
"body": stringValue("undo 통합 테스트"),
"receivedAt": timestampValue(Date()),
"isRead": booleanValue(false),
"todoId": stringValue("todo-\(notificationId)"),
"todoCategory": stringValue("feature"),
"isDeleted": booleanValue(false)
]
try await upsertDocument(
documentPath: "users/\(userId)/notifications/\(notificationId)",
fields: fields
)
return notificationId
}
func seedWebPage(
userId: String,
documentId: String = UUID().uuidString,
urlString: String = "https://example.com/\(UUID().uuidString)"
) async throws -> SeededWebPage {
let fields = [
"title": stringValue("Example"),
"url": stringValue(urlString),
"displayURL": stringValue(urlString),
"imageURL": stringValue(""),
"isDeleted": booleanValue(false)
]
try await upsertDocument(
documentPath: "users/\(userId)/webPages/\(documentId)",
fields: fields
)
return SeededWebPage(
documentId: documentId,
urlString: urlString
)
}
func requestPushNotificationDeletion(
notificationId: String,
idToken: String
) async throws {
_ = try await callFunction(
name: "requestPushNotificationDeletion",
idToken: idToken,
data: ["notificationId": notificationId]
)
}
func undoPushNotificationDeletion(
notificationId: String,
idToken: String
) async throws {
_ = try await callFunction(
name: "undoPushNotificationDeletion",
idToken: idToken,
data: ["notificationId": notificationId]
)
}
func requestWebPageDeletion(
urlString: String,
idToken: String
) async throws {
_ = try await callFunction(
name: "requestWebPageDeletion",
idToken: idToken,
data: ["urlString": urlString]
)
}
func undoWebPageDeletion(
urlString: String,
idToken: String
) async throws {
_ = try await callFunction(
name: "undoWebPageDeletion",
idToken: idToken,
data: ["urlString": urlString]
)
}
func fetchPushNotificationIDs(userId: String) async throws -> [String] {
let googleServiceInfo = try loadGoogleServiceInfo()
let url = firestoreBaseURL.appending(
path: "v1/projects/\(googleServiceInfo.projectId)/databases/(default)/documents/users/" +
"\(userId)/notifications",
directoryHint: .notDirectory
)
let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse else {
throw RESTError.invalidResponse
}
guard 200 ..< 300 ~= httpResponse.statusCode else {
let body = String(data: data, encoding: .utf8) ?? ""
throw RESTError.unsuccessfulStatusCode(httpResponse.statusCode, body)
}
let payload = try decodeJSON(data)
let documents = payload["documents"] as? [[String: Any]] ?? []
return documents.compactMap { document in
guard
let name = document["name"] as? String,
let fields = document["fields"] as? [String: [String: Any]],
boolValue(for: "isDeleted", in: fields) != true
else {
return nil
}
return name.split(separator: "/").last.map(String.init)
}
}
func fetchWebPageURLs(userId: String) async throws -> [String] {
let googleServiceInfo = try loadGoogleServiceInfo()
let url = firestoreBaseURL.appending(
path: "v1/projects/\(googleServiceInfo.projectId)/databases/(default)/documents/users/\(userId)/webPages",
directoryHint: .notDirectory
)
let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse else {
throw RESTError.invalidResponse
}
guard 200 ..< 300 ~= httpResponse.statusCode else {
let body = String(data: data, encoding: .utf8) ?? ""
throw RESTError.unsuccessfulStatusCode(httpResponse.statusCode, body)
}
let payload = try decodeJSON(data)
let documents = payload["documents"] as? [[String: Any]] ?? []
return documents.compactMap { document in
guard
let fields = document["fields"] as? [String: [String: Any]],
boolValue(for: "isDeleted", in: fields) != true
else {
return nil
}
return fields["url"]?["stringValue"] as? String
}
}
func waitUntil(
timeout: Duration = .seconds(3),
pollInterval: Duration = .milliseconds(100),
_ condition: @escaping () async throws -> Bool
) async throws {
let continuousClock = ContinuousClock()
let deadline = continuousClock.now + timeout
while continuousClock.now < deadline {
if try await condition() {
return
}
try await Task.sleep(for: pollInterval)
}
throw RESTError.timedOut
}
}
private extension LocalFirebaseRESTSupport {
struct GoogleServiceInfo {
let apiKey: String
let projectId: String
}
enum RESTError: Error {
case invalidResponse
case unsuccessfulStatusCode(Int, String)
case missingConfiguration
case timedOut
}
func loadGoogleServiceInfo() throws -> GoogleServiceInfo {
var fileURL = URL(fileURLWithPath: #filePath)
while fileURL.lastPathComponent != "DevLog_iOS" {
let nextURL = fileURL.deletingLastPathComponent()
if nextURL == fileURL {
throw RESTError.missingConfiguration
}
fileURL = nextURL
}
let plistURL = fileURL
.appending(path: "DevLog")
.appending(path: "Resource")
.appending(path: "GoogleService-Info.plist")
let data = try Data(contentsOf: plistURL)
guard
let payload = try PropertyListSerialization.propertyList(
from: data,
options: [],
format: nil
) as? [String: Any],
let apiKey = payload["API_KEY"] as? String,
let projectId = payload["PROJECT_ID"] as? String
else {
throw RESTError.missingConfiguration
}
return GoogleServiceInfo(
apiKey: apiKey,
projectId: projectId
)
}
func callFunction(
name: String,
idToken: String,
data: [String: Any]
) async throws -> [String: Any] {
let googleServiceInfo = try loadGoogleServiceInfo()
var request = URLRequest(
url: functionsBaseURL.appending(
path: "\(googleServiceInfo.projectId)/asia-northeast3/\(name)",
directoryHint: .notDirectory
)
)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(idToken)", forHTTPHeaderField: "Authorization")
request.httpBody = try JSONSerialization.data(withJSONObject: ["data": data])
return try await sendJSON(request)
}
func upsertDocument(
documentPath: String,
fields: [String: [String: Any]]
) async throws {
let googleServiceInfo = try loadGoogleServiceInfo()
let encodedPath = encode(documentPath)
var request = URLRequest(
url: firestoreBaseURL.appending(
path: "v1/projects/\(googleServiceInfo.projectId)/databases/(default)/documents/\(encodedPath)",
directoryHint: .notDirectory
)
)
request.httpMethod = "PATCH"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONSerialization.data(withJSONObject: ["fields": fields])
_ = try await sendJSON(request)
}
func sendJSON(_ request: URLRequest) async throws -> [String: Any] {
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw RESTError.invalidResponse
}
guard 200 ..< 300 ~= httpResponse.statusCode else {
let body = String(data: data, encoding: .utf8) ?? ""
throw RESTError.unsuccessfulStatusCode(httpResponse.statusCode, body)
}
return try decodeJSON(data)
}
func decodeJSON(_ data: Data) throws -> [String: Any] {
guard let payload = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
throw RESTError.invalidResponse
}
return payload
}
func encode(_ path: String) -> String {
path.split(separator: "/").map {
String($0).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? String($0)
}.joined(separator: "/")
}
func stringValue(_ value: String) -> [String: Any] {
["stringValue": value]
}
func booleanValue(_ value: Bool) -> [String: Any] {
["booleanValue": value]
}
func timestampValue(_ value: Date) -> [String: Any] {
["timestampValue": value.formatted(.iso8601)]
}
func boolValue(
for field: String,
in fields: [String: [String: Any]]?
) -> Bool? {
fields?[field]?["booleanValue"] as? Bool
}
}