BasicCompileTests.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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("tags", notIn: ["active", "squat"])
  81. .whereField(FieldPath(["tags"]), notIn: ["active", "squat"])
  82. .whereField(FieldPath.documentID(), isEqualTo: "fred")
  83. .whereField(FieldPath.documentID(), isNotEqualTo: "fred")
  84. .whereField(FieldPath(["name"]), isEqualTo: "fred")
  85. .order(by: FieldPath(["age"]))
  86. .order(by: "name", descending: true)
  87. .limit(to: 10)
  88. .limit(toLast: 10)
  89. query = collectionRef.firestore.collectionGroup("collection")
  90. return query
  91. }
  92. func writeDocument(at docRef: DocumentReference) {
  93. let setData = [
  94. "foo": 42,
  95. "bar": [
  96. "baz": "Hello world!",
  97. ],
  98. ] as [String: Any]
  99. let updateData = [
  100. "bar.baz": 42,
  101. FieldPath(["foobar"]): 42,
  102. "server_timestamp": FieldValue.serverTimestamp(),
  103. "array_union": FieldValue.arrayUnion(["a", "b"]),
  104. "array_remove": FieldValue.arrayRemove(["a", "b"]),
  105. "field_delete": FieldValue.delete(),
  106. ] as [AnyHashable: Any]
  107. docRef.setData(setData)
  108. // Completion callback (via trailing closure syntax).
  109. docRef.setData(setData) { error in
  110. if let error = error {
  111. print("Uh oh! \(error)")
  112. return
  113. }
  114. print("Set complete!")
  115. }
  116. // merge
  117. docRef.setData(setData, merge: true)
  118. docRef.setData(setData, merge: true) { error in
  119. if let error = error {
  120. print("Uh oh! \(error)")
  121. return
  122. }
  123. print("Set complete!")
  124. }
  125. docRef.updateData(updateData)
  126. docRef.delete()
  127. docRef.delete { error in
  128. if let error = error {
  129. print("Uh oh! \(error)")
  130. return
  131. }
  132. print("Set complete!")
  133. }
  134. }
  135. func enableDisableNetwork(database db: Firestore) {
  136. // closure syntax
  137. db.disableNetwork(completion: { error in
  138. if let e = error {
  139. print("Uh oh! \(e)")
  140. return
  141. }
  142. })
  143. // trailing block syntax
  144. db.enableNetwork { error in
  145. if let e = error {
  146. print("Uh oh! \(e)")
  147. return
  148. }
  149. }
  150. }
  151. func clearPersistence(database db: Firestore) {
  152. db.clearPersistence { error in
  153. if let e = error {
  154. print("Uh oh! \(e)")
  155. return
  156. }
  157. }
  158. }
  159. func writeDocuments(at docRef: DocumentReference, database db: Firestore) {
  160. var batch: WriteBatch
  161. batch = db.batch()
  162. batch.setData(["a": "b"], forDocument: docRef)
  163. batch.setData(["a": "b"], forDocument: docRef, merge: true)
  164. batch.setData(["c": "d"], forDocument: docRef)
  165. // commit without completion callback.
  166. batch.commit()
  167. print("Batch write without completion complete!")
  168. batch = db.batch()
  169. batch.setData(["a": "b"], forDocument: docRef)
  170. batch.setData(["c": "d"], forDocument: docRef)
  171. // commit with completion callback via trailing closure syntax.
  172. batch.commit { error in
  173. if let error = error {
  174. print("Uh oh! \(error)")
  175. return
  176. }
  177. print("Batch write callback complete!")
  178. }
  179. print("Batch write with completion complete!")
  180. }
  181. func addDocument(to collectionRef: CollectionReference) {
  182. _ = collectionRef.addDocument(data: ["foo": 42])
  183. // or
  184. collectionRef.document().setData(["foo": 42])
  185. }
  186. func readDocument(at docRef: DocumentReference) {
  187. // Trailing closure syntax.
  188. docRef.getDocument { document, error in
  189. if let document = document {
  190. // Note that both document and document.data() is nullable.
  191. if let data = document.data() {
  192. print("Read document: \(data)")
  193. }
  194. if let data = document.data(with: .estimate) {
  195. print("Read document: \(data)")
  196. }
  197. if let foo = document.get("foo") {
  198. print("Field: \(foo)")
  199. }
  200. if let foo = document.get("foo", serverTimestampBehavior: .previous) {
  201. print("Field: \(foo)")
  202. }
  203. // Fields can also be read via subscript notation.
  204. if let foo = document["foo"] {
  205. print("Field: \(foo)")
  206. }
  207. } else {
  208. // TODO(mikelehen): There may be a better way to do this, but it at least demonstrates
  209. // the swift error domain / enum codes are renamed appropriately.
  210. if let errorCode = error.flatMap({
  211. ($0._domain == FirestoreErrorDomain) ? FirestoreErrorCode(rawValue: $0._code) : nil
  212. }) {
  213. switch errorCode {
  214. case .unavailable:
  215. print("Can't read document due to being offline!")
  216. case _:
  217. print("Failed to read.")
  218. }
  219. } else {
  220. print("Unknown error!")
  221. }
  222. }
  223. }
  224. }
  225. func readDocumentWithSource(at docRef: DocumentReference) {
  226. docRef.getDocument(source: FirestoreSource.default) { document, error in
  227. }
  228. docRef.getDocument(source: .server) { document, error in
  229. }
  230. docRef.getDocument(source: FirestoreSource.cache) { document, error in
  231. }
  232. }
  233. func readDocuments(matching query: Query) {
  234. query.getDocuments { querySnapshot, error in
  235. // TODO(mikelehen): Figure out how to make "for..in" syntax work
  236. // directly on documentSet.
  237. for document in querySnapshot!.documents {
  238. print(document.data())
  239. }
  240. }
  241. }
  242. func readDocumentsWithSource(matching query: Query) {
  243. query.getDocuments(source: FirestoreSource.default) { querySnapshot, error in
  244. }
  245. query.getDocuments(source: .server) { querySnapshot, error in
  246. }
  247. query.getDocuments(source: FirestoreSource.cache) { querySnapshot, error in
  248. }
  249. }
  250. func listenToDocument(at docRef: DocumentReference) {
  251. let listener = docRef.addSnapshotListener { document, error in
  252. if let error = error {
  253. print("Uh oh! Listen canceled: \(error)")
  254. return
  255. }
  256. if let document = document {
  257. // Note that document.data() is nullable.
  258. if let data: [String: Any] = document.data() {
  259. print("Current document: \(data)")
  260. }
  261. if document.metadata.isFromCache {
  262. print("From Cache")
  263. } else {
  264. print("From Server")
  265. }
  266. }
  267. }
  268. // Unsubscribe.
  269. listener.remove()
  270. }
  271. func listenToDocumentWithMetadataChanges(at docRef: DocumentReference) {
  272. let listener = docRef.addSnapshotListener(includeMetadataChanges: true) { document, error in
  273. if let document = document {
  274. if document.metadata.hasPendingWrites {
  275. print("Has pending writes")
  276. }
  277. }
  278. }
  279. // Unsubscribe.
  280. listener.remove()
  281. }
  282. func listenToDocuments(matching query: Query) {
  283. let listener = query.addSnapshotListener { snap, error in
  284. if let error = error {
  285. print("Uh oh! Listen canceled: \(error)")
  286. return
  287. }
  288. if let snap = snap {
  289. print("NEW SNAPSHOT (empty=\(snap.isEmpty) count=\(snap.count)")
  290. // TODO(mikelehen): Figure out how to make "for..in" syntax work
  291. // directly on documentSet.
  292. for document in snap.documents {
  293. // Note that document.data() is not nullable.
  294. let data: [String: Any] = document.data()
  295. print("Doc: ", data)
  296. }
  297. }
  298. }
  299. // Unsubscribe
  300. listener.remove()
  301. }
  302. func listenToQueryDiffs(onQuery query: Query) {
  303. let listener = query.addSnapshotListener { snap, error in
  304. if let snap = snap {
  305. for change in snap.documentChanges {
  306. switch change.type {
  307. case .added:
  308. print("New document: \(change.document.data())")
  309. case .modified:
  310. print("Modified document: \(change.document.data())")
  311. case .removed:
  312. print("Removed document: \(change.document.data())")
  313. }
  314. }
  315. }
  316. }
  317. // Unsubscribe
  318. listener.remove()
  319. }
  320. func listenToQueryDiffsWithMetadata(onQuery query: Query) {
  321. let listener = query.addSnapshotListener(includeMetadataChanges: true) { snap, error in
  322. if let snap = snap {
  323. for change in snap.documentChanges(includeMetadataChanges: true) {
  324. switch change.type {
  325. case .added:
  326. print("New document: \(change.document.data())")
  327. case .modified:
  328. print("Modified document: \(change.document.data())")
  329. case .removed:
  330. print("Removed document: \(change.document.data())")
  331. }
  332. }
  333. }
  334. }
  335. // Unsubscribe
  336. listener.remove()
  337. }
  338. func transactions() {
  339. let db = Firestore.firestore()
  340. let collectionRef = db.collection("cities")
  341. let accA = collectionRef.document("accountA")
  342. let accB = collectionRef.document("accountB")
  343. let amount = 20.0
  344. db.runTransaction({ (transaction, errorPointer) -> Any? in
  345. do {
  346. let balanceA = try transaction.getDocument(accA)["balance"] as! Double
  347. let balanceB = try transaction.getDocument(accB)["balance"] as! Double
  348. if balanceA < amount {
  349. errorPointer?.pointee = NSError(domain: "Foo", code: 123, userInfo: nil)
  350. return nil
  351. }
  352. transaction.updateData(["balance": balanceA - amount], forDocument: accA)
  353. transaction.updateData(["balance": balanceB + amount], forDocument: accB)
  354. } catch let error as NSError {
  355. print("Uh oh! \(error)")
  356. }
  357. return 0
  358. }) { result, error in
  359. // handle result.
  360. }
  361. }
  362. func types() {
  363. let _: CollectionReference
  364. let _: DocumentChange
  365. let _: DocumentReference
  366. let _: DocumentSnapshot
  367. let _: FieldPath
  368. let _: FieldValue
  369. let _: Firestore
  370. let _: FirestoreSettings
  371. let _: GeoPoint
  372. let _: Timestamp
  373. let _: ListenerRegistration
  374. let _: Query
  375. let _: QuerySnapshot
  376. let _: SnapshotMetadata
  377. let _: Transaction
  378. let _: WriteBatch
  379. }
  380. func waitForPendingWrites(database db: Firestore) {
  381. db.waitForPendingWrites { error in
  382. if let e = error {
  383. print("Uh oh! \(e)")
  384. return
  385. }
  386. }
  387. }
  388. func addSnapshotsInSyncListener(database db: Firestore) {
  389. let listener = db.addSnapshotsInSyncListener {}
  390. // Unsubscribe
  391. listener.remove()
  392. }
  393. func terminateDb(database db: Firestore) {
  394. db.terminate { error in
  395. if let e = error {
  396. print("Uh oh! \(e)")
  397. return
  398. }
  399. }
  400. }