Skip to content

Commit

Permalink
ユーザー検索をemailとusernameがヒットするように修正
Browse files Browse the repository at this point in the history
  • Loading branch information
boardguy1024 committed Oct 21, 2023
1 parent fbd2d46 commit dd7a28b
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 14 deletions.
Binary file not shown.
1 change: 1 addition & 0 deletions TwitterSwiftUI/Service/AuthService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class AuthService: ObservableObject {
let userDataDic = ["email": email,
// 検索でユーザーを小文字でヒットさせるための工夫
"username_lowercase": username.lowercased(),
"emailUsername_lowercase": email.emailUsername?.lowercased() ?? "",
"username": username,
"uid": user.uid]

Expand Down
72 changes: 58 additions & 14 deletions TwitterSwiftUI/Service/UserService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import Firebase
import FirebaseFirestore
import Combine

class UserService {

Expand Down Expand Up @@ -39,21 +40,64 @@ class UserService {
// ヒットしたユーザーリストを取得
func fetchUsers(with query: String) async throws -> [User] {
guard !query.isEmpty else { return [] }

let lowercasedQuery = query.lowercased()
do {
let snapshot = try await Firestore.firestore().collection("users")
.whereField("username_lowercase", isGreaterThanOrEqualTo: lowercasedQuery)
.whereField("username_lowercase", isLessThan: lowercasedQuery + "\u{f8ff}")
.getDocuments()
let firestore = Firestore.firestore()

// Publisher for fetching users by username_lowercase
@Sendable func usersByUsername() -> Future<[User], Error> {
return Future { promise in
Task {
do {
let snapshot = try await firestore.collection("users")
.whereField("username_lowercase", isGreaterThanOrEqualTo: lowercasedQuery)
.whereField("username_lowercase", isLessThan: lowercasedQuery + "\u{f8ff}")
.getDocuments()

let users = snapshot.documents.compactMap({ try? $0.data(as: User.self) })
promise(.success(users))
} catch {
promise(.failure(error))
}
}
}
}

@Sendable func usersByEmail() -> Future<[User], Error> {
return Future { promise in
Task {
do {
let snapshot = try await firestore.collection("users")
.whereField("emailUsername_lowercase", isGreaterThanOrEqualTo: lowercasedQuery)
.whereField("emailUsername_lowercase", isLessThan: lowercasedQuery + "\u{f8ff}")
.getDocuments()

let users = snapshot.documents.compactMap({ try? $0.data(as: User.self) })
promise(.success(users))
} catch {
promise(.failure(error))
}
}
}
}

// Use CombineLatest to fetch both username and email results and combine them
let users = try await withThrowingTaskGroup(of: [User].self) { group in
group.addTask { try await usersByEmail().value }
group.addTask { try await usersByUsername().value }

return snapshot.documents.compactMap({ try? $0.data(as: User.self) })
} catch {
print("DEBUG: Failed fetchUsersWithQuery: \(error.localizedDescription)")
return []
var combinedUsers: [User] = []
for try await users in group {
combinedUsers.append(contentsOf: users)
}

return combinedUsers
}

return users
}

func updateProfile(profileImage: UIImage?,
func updateProfile(profileImage: UIImage?,
headerImage: UIImage?,
name: String?,
bio: String?,
Expand All @@ -65,22 +109,22 @@ class UserService {

try await tryUploadImage(dataDic: &data, uploadImage: profileImage, using: ImageUploader.uploadProfileImage, key: "profileImageUrl")
try await tryUploadImage(dataDic: &data, uploadImage: headerImage, using: ImageUploader.uploadProfileImage, key: "profileHeaderImageUrl")

addIfNotEmpty(dataDic: &data, value: name, forKey: "username")
addIfNotEmpty(dataDic: &data, value: bio, forKey: "bio")
addIfNotEmpty(dataDic: &data, value: location, forKey: "location")
addIfNotEmpty(dataDic: &data, value: webUrl, forKey: "webUrl")

try await Firestore.firestore().collection("users")
.document(uid)
.updateData(data)

try await AuthService.shared.refreshCurrentUser()

}

// Helper functions

private func tryUploadImage(dataDic: inout [String: Any],
uploadImage: UIImage?,
using uploader: (UIImage) async throws -> String?, key: String) async throws {
Expand Down

0 comments on commit dd7a28b

Please sign in to comment.