@@ -371,6 +371,62 @@ extension FirestoreService: FirestoreQueryable {
371371 }
372372 } . eraseToAnyPublisher ( )
373373 }
374+
375+ /// Checks if a document is duplicated or not from the endpoint requestType is a collectionRef using firestore's query.
376+ ///
377+ /// Notes:
378+ /// 1. This method executes a Firestore query to check if the specified field in the document is duplicated from a collection reference.
379+ /// 2. endpoint's a documentRef computed property of requestType property should return nil.
380+ /// 3. The query is executed using the provided endpoint and query handler.
381+ /// 4. The requestType of endpoint is not used.
382+ ///
383+ /// - Parameters:
384+ /// - endpoint: The Firestore endpoint to query, which must conform to `FirestoreEndopintable`.
385+ /// - query: The Firestore query handler used to execute the query.
386+ /// The query should be designed to check for field duplication.
387+ /// - Returns: A publisher that emits a `Bool` indicating whether the field is duplicated (`true`) or not (`false`).
388+ /// - Throws: `FirestoreServiceError` if the query execution fails.
389+ ///
390+ /// Example:
391+ /// - Does a document with test1 exist in the user's collection?
392+ /// ```
393+ /// let editedUserName = "test1"
394+ /// let endpoint: FirestoreEndpointable = UserAPIEndpoint()
395+ /// FirestoreService().isFieldDuplicated(endpoint: endpoint) { collectionReference in
396+ /// return collectionReference
397+ /// .whereField("username", isEqualTo: editedUserName)
398+ /// }.receive(on: DispatchQueue.main)
399+ /// .map { isFieldDuplicated in
400+ /// // TODO: - You can check whether the query has any matching documents in this downstream
401+ /// }
402+ /// ```
403+ public func isFieldDuplicated(
404+ endpoint: any FirestoreEndopintable ,
405+ makeQuery: @escaping FirestoreQueryHandler
406+ ) -> AnyPublisher < Bool , FirestoreServiceError > {
407+ return Future < Bool , FirestoreServiceError > { promise in
408+ guard let collectionRef = endpoint. requestType. asCollectionRef else {
409+ promise ( . failure( . collectionNotFound) )
410+ return
411+ }
412+ do {
413+ let query = try makeQuery ( collectionRef)
414+ query. getDocuments { querySnapshot, error in
415+ if let error = error {
416+ promise ( . failure( . wrappedfirestoreError( error) ) )
417+ return
418+ }
419+ if let documents = querySnapshot? . documents, !documents. isEmpty {
420+ promise ( . success( true ) )
421+ return
422+ }
423+ promise ( . success( false ) )
424+ }
425+ } catch {
426+ promise ( . failure( . wrappedfirestoreError( error) ) )
427+ }
428+ } . eraseToAnyPublisher ( )
429+ }
374430}
375431
376432// MARK: - FirestoreTransactional
0 commit comments