BasicCompileTests.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. // These aren't tests in the usual sense--they just verify that the Objective-C to Swift translation
  17. // results in the right names.
  18. import Foundation
  19. import XCTest
  20. import FirebaseFirestore
  21. class BasicCompileTests: XCTestCase {
  22. func testCompiled() {
  23. XCTAssertTrue(true)
  24. }
  25. }
  26. func main() {
  27. let db = initializeDb()
  28. let (collectionRef, documentRef) = makeRefs(database: db)
  29. let query = makeQuery(collection: collectionRef)
  30. writeDocument(at: documentRef)
  31. writeDocuments(at: documentRef, database: db)
  32. addDocument(to: collectionRef)
  33. readDocument(at: documentRef)
  34. readDocumentWithSource(at: documentRef)
  35. readDocuments(matching: query)
  36. readDocumentsWithSource(matching: query)
  37. listenToDocument(at: documentRef)
  38. listenToDocuments(matching: query)
  39. enableDisableNetwork(database: db)
  40. clearPersistence(database: db)
  41. types()
  42. waitForPendingWrites(database: db)
  43. addSnapshotsInSyncListener(database: db)
  44. terminateDb(database: db)
  45. }
  46. func initializeDb() -> Firestore {
  47. // Initialize with ProjectID.
  48. let firestore = Firestore.firestore()
  49. // Apply settings
  50. let settings = FirestoreSettings()
  51. settings.host = "localhost"
  52. settings.isPersistenceEnabled = true
  53. settings.cacheSizeBytes = FirestoreCacheSizeUnlimited
  54. firestore.settings = settings
  55. return firestore
  56. }
  57. func makeRefs(database db: Firestore) -> (CollectionReference, DocumentReference) {
  58. var collectionRef = db.collection("my-collection")
  59. var documentRef: DocumentReference
  60. documentRef = collectionRef.document("my-doc")
  61. // or
  62. documentRef = db.document("my-collection/my-doc")
  63. // deeper collection (my-collection/my-doc/some/deep/collection)
  64. collectionRef = documentRef.collection("some/deep/collection")
  65. // parent doc (my-collection/my-doc/some/deep)
  66. documentRef = collectionRef.parent!
  67. // print paths.
  68. print("Collection: \(collectionRef.path), document: \(documentRef.path)")
  69. return (collectionRef, documentRef)
  70. }
  71. func makeQuery(collection collectionRef: CollectionReference) -> Query {
  72. var query = collectionRef.whereField(FieldPath(["name"]), isEqualTo: "Fred")
  73. .whereField("age", isGreaterThanOrEqualTo: 24)
  74. .whereField("tags", arrayContains: "active")
  75. .whereField(FieldPath(["tags"]), arrayContains: "active")
  76. .whereField("tags", arrayContainsAny: ["active", "squat"])
  77. .whereField(FieldPath(["tags"]), arrayContainsAny: ["active", "squat"])
  78. .whereField("tags", in: ["active", "squat"])
  79. .whereField(FieldPath(["tags"]), in: ["active", "squat"])
  80. .whereField(FieldPath.documentID(), isEqualTo: "fred")
  81. .order(by: FieldPath(["age"]))
  82. .order(by: "name", descending: true)
  83. .limit(to: 10)
  84. .limit(toLast: 10)
  85. query = collectionRef.firestore.collectionGroup("collection")
  86. return query
  87. }
  88. func writeDocument(at docRef: DocumentReference) {
  89. let setData = [
  90. "foo": 42,
  91. "bar": [
  92. "baz": "Hello world!",
  93. ],
  94. ] as [String: Any]
  95. let updateData = [
  96. "bar.baz": 42,
  97. FieldPath(["foobar"]): 42,
  98. "server_timestamp": FieldValue.serverTimestamp(),
  99. "array_union": FieldValue.arrayUnion(["a", "b"]),
  100. "array_remove": FieldValue.arrayRemove(["a", "b"]),
  101. "field_delete": FieldValue.delete(),
  102. ] as [AnyHashable: Any]
  103. docRef.setData(setData)
  104. // Completion callback (via trailing closure syntax).
  105. docRef.setData(setData) { error in
  106. if let error = error {
  107. print("Uh oh! \(error)")
  108. return
  109. }
  110. print("Set complete!")
  111. }
  112. // merge
  113. docRef.setData(setData, merge: true)
  114. docRef.setData(setData, merge: true) { error in
  115. if let error = error {
  116. print("Uh oh! \(error)")
  117. return
  118. }
  119. print("Set complete!")
  120. }
  121. docRef.updateData(updateData)
  122. docRef.delete()
  123. docRef.delete { error in
  124. if let error = error {
  125. print("Uh oh! \(error)")
  126. return
  127. }
  128. print("Set complete!")
  129. }
  130. }
  131. func enableDisableNetwork(database db: Firestore) {
  132. // closure syntax
  133. db.disableNetwork(completion: { error in
  134. if let e = error {
  135. print("Uh oh! \(e)")
  136. return
  137. }
  138. })
  139. // trailing block syntax
  140. db.enableNetwork { error in
  141. if let e = error {
  142. print("Uh oh! \(e)")
  143. return
  144. }
  145. }
  146. }
  147. func clearPersistence(database db: Firestore) {
  148. db.clearPersistence { error in
  149. if let e = error {
  150. print("Uh oh! \(e)")
  151. return
  152. }
  153. }
  154. }
  155. func writeDocuments(at docRef: DocumentReference, database db: Firestore) {
  156. var batch: WriteBatch
  157. batch = db.batch()
  158. batch.setData(["a": "b"], forDocument: docRef)
  159. batch.setData(["a": "b"], forDocument: docRef, merge: true)
  160. batch.setData(["c": "d"], forDocument: docRef)
  161. // commit without completion callback.
  162. batch.commit()
  163. print("Batch write without completion complete!")
  164. batch = db.batch()
  165. batch.setData(["a": "b"], forDocument: docRef)
  166. batch.setData(["c": "d"], forDocument: docRef)
  167. // commit with completion callback via trailing closure syntax.
  168. batch.commit { error in
  169. if let error = error {
  170. print("Uh oh! \(error)")
  171. return
  172. }
  173. print("Batch write callback complete!")
  174. }
  175. print("Batch write with completion complete!")
  176. }
  177. func addDocument(to collectionRef: CollectionReference) {
  178. _ = collectionRef.addDocument(data: ["foo": 42])
  179. // or
  180. collectionRef.document().setData(["foo": 42])
  181. }
  182. func readDocument(at docRef: DocumentReference) {
  183. // Trailing closure syntax.
  184. docRef.getDocument { document, error in
  185. if let document = document {
  186. // Note that both document and document.data() is nullable.
  187. if let data = document.data() {
  188. print("Read document: \(data)")
  189. }
  190. if let data = document.data(with: .estimate) {
  191. print("Read document: \(data)")
  192. }
  193. if let foo = document.get("foo") {
  194. print("Field: \(foo)")
  195. }
  196. if let foo = document.get("foo", serverTimestampBehavior: .previous) {
  197. print("Field: \(foo)")
  198. }
  199. // Fields can also be read via subscript notation.
  200. if let foo = document["foo"] {
  201. print("Field: \(foo)")
  202. }
  203. } else {
  204. // TODO(mikelehen): There may be a better way to do this, but it at least demonstrates
  205. // the swift error domain / enum codes are renamed appropriately.
  206. if let errorCode = error.flatMap({
  207. ($0._domain == FirestoreErrorDomain) ? FirestoreErrorCode(rawValue: $0._code) : nil
  208. }) {
  209. switch errorCode {
  210. case .unavailable:
  211. print("Can't read document due to being offline!")
  212. case _:
  213. print("Failed to read.")
  214. }
  215. } else {
  216. print("Unknown error!")
  217. }
  218. }
  219. }
  220. }
  221. func readDocumentWithSource(at docRef: DocumentReference) {
  222. docRef.getDocument(source: FirestoreSource.default) { document, error in
  223. }
  224. docRef.getDocument(source: .server) { document, error in
  225. }
  226. docRef.getDocument(source: FirestoreSource.cache) { document, error in
  227. }
  228. }
  229. func readDocuments(matching query: Query) {
  230. query.getDocuments { querySnapshot, error in
  231. // TODO(mikelehen): Figure out how to make "for..in" syntax work
  232. // directly on documentSet.
  233. for document in querySnapshot!.documents {
  234. print(document.data())
  235. }
  236. }
  237. }
  238. func readDocumentsWithSource(matching query: Query) {
  239. query.getDocuments(source: FirestoreSource.default) { querySnapshot, error in
  240. }
  241. query.getDocuments(source: .server) { querySnapshot, error in
  242. }
  243. query.getDocuments(source: FirestoreSource.cache) { querySnapshot, error in
  244. }
  245. }
  246. func listenToDocument(at docRef: DocumentReference) {
  247. let listener = docRef.addSnapshotListener { document, error in
  248. if let error = error {
  249. print("Uh oh! Listen canceled: \(error)")
  250. return
  251. }
  252. if let document = document {
  253. // Note that document.data() is nullable.
  254. if let data: [String: Any] = document.data() {
  255. print("Current document: \(data)")
  256. }
  257. if document.metadata.isFromCache {
  258. print("From Cache")
  259. } else {
  260. print("From Server")
  261. }
  262. }
  263. }
  264. // Unsubscribe.
  265. listener.remove()
  266. }
  267. func listenToDocumentWithMetadataChanges(at docRef: DocumentReference) {
  268. let listener = docRef.addSnapshotListener(includeMetadataChanges: true) { document, error in
  269. if let document = document {
  270. if document.metadata.hasPendingWrites {
  271. print("Has pending writes")
  272. }
  273. }
  274. }
  275. // Unsubscribe.
  276. listener.remove()
  277. }
  278. func listenToDocuments(matching query: Query) {
  279. let listener = query.addSnapshotListener { snap, error in
  280. if let error = error {
  281. print("Uh oh! Listen canceled: \(error)")
  282. return
  283. }
  284. if let snap = snap {
  285. print("NEW SNAPSHOT (empty=\(snap.isEmpty) count=\(snap.count)")
  286. // TODO(mikelehen): Figure out how to make "for..in" syntax work
  287. // directly on documentSet.
  288. for document in snap.documents {
  289. // Note that document.data() is not nullable.
  290. let data: [String: Any] = document.data()
  291. print("Doc: ", data)
  292. }
  293. }
  294. }
  295. // Unsubscribe
  296. listener.remove()
  297. }
  298. func listenToQueryDiffs(onQuery query: Query) {
  299. let listener = query.addSnapshotListener { snap, error in
  300. if let snap = snap {
  301. for change in snap.documentChanges {
  302. switch change.type {
  303. case .added:
  304. print("New document: \(change.document.data())")
  305. case .modified:
  306. print("Modified document: \(change.document.data())")
  307. case .removed:
  308. print("Removed document: \(change.document.data())")
  309. }
  310. }
  311. }
  312. }
  313. // Unsubscribe
  314. listener.remove()
  315. }
  316. func listenToQueryDiffsWithMetadata(onQuery query: Query) {
  317. let listener = query.addSnapshotListener(includeMetadataChanges: true) { snap, error in
  318. if let snap = snap {
  319. for change in snap.documentChanges(includeMetadataChanges: true) {
  320. switch change.type {
  321. case .added:
  322. print("New document: \(change.document.data())")
  323. case .modified:
  324. print("Modified document: \(change.document.data())")
  325. case .removed:
  326. print("Removed document: \(change.document.data())")
  327. }
  328. }
  329. }
  330. }
  331. // Unsubscribe
  332. listener.remove()
  333. }
  334. func transactions() {
  335. let db = Firestore.firestore()
  336. let collectionRef = db.collection("cities")
  337. let accA = collectionRef.document("accountA")
  338. let accB = collectionRef.document("accountB")
  339. let amount = 20.0
  340. db.runTransaction({ (transaction, errorPointer) -> Any? in
  341. do {
  342. let balanceA = try transaction.getDocument(accA)["balance"] as! Double
  343. let balanceB = try transaction.getDocument(accB)["balance"] as! Double
  344. if balanceA < amount {
  345. errorPointer?.pointee = NSError(domain: "Foo", code: 123, userInfo: nil)
  346. return nil
  347. }
  348. transaction.updateData(["balance": balanceA - amount], forDocument: accA)
  349. transaction.updateData(["balance": balanceB + amount], forDocument: accB)
  350. } catch let error as NSError {
  351. print("Uh oh! \(error)")
  352. }
  353. return 0
  354. }) { result, error in
  355. // handle result.
  356. }
  357. }
  358. func types() {
  359. let _: CollectionReference
  360. let _: DocumentChange
  361. let _: DocumentReference
  362. let _: DocumentSnapshot
  363. let _: FieldPath
  364. let _: FieldValue
  365. let _: Firestore
  366. let _: FirestoreSettings
  367. let _: GeoPoint
  368. let _: Timestamp
  369. let _: ListenerRegistration
  370. let _: Query
  371. let _: QuerySnapshot
  372. let _: SnapshotMetadata
  373. let _: Transaction
  374. let _: WriteBatch
  375. }
  376. func waitForPendingWrites(database db: Firestore) {
  377. db.waitForPendingWrites { error in
  378. if let e = error {
  379. print("Uh oh! \(e)")
  380. return
  381. }
  382. }
  383. }
  384. func addSnapshotsInSyncListener(database db: Firestore) {
  385. let listener = db.addSnapshotsInSyncListener {}
  386. // Unsubscribe
  387. listener.remove()
  388. }
  389. func terminateDb(database db: Firestore) {
  390. db.terminate { error in
  391. if let e = error {
  392. print("Uh oh! \(e)")
  393. return
  394. }
  395. }
  396. }