BasicCompileTests.swift 11 KB

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