BasicCompileTests.swift 12 KB

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