24.03.05 FireBase 색인과 규칙

KSang·2024년 3월 6일
0

TIL

목록 보기
80/101
post-thumbnail

파이어 베이스는 데이터 베이스를 규칙으로 데이터를 읽고 쓰게 할 수 있다.

이는 콘솔에서 설정하는데,

RealTimeDataBase, FireStore, Storage등 데이터 베이스들에 설정을 한다.

{
  "rules": {
    "chatRooms": {
      ".write": true,
      ".read": true,
    	}
    }
}

이런식으로 설정하면 모든 유저들이 채팅 방에 어떻게 접근을 하게되면 대화내역을 보며 채팅을 칠 수 있을것 이다.

이런 위험을 방지하기 위해 규칙을 정해줄 수 있다.

{
  "rules": {
    "chatRooms": {
      ".write": true,
      ".read": "auth != null",
      "$chatRoomId": {
        ".read": "data.child('participantsUid').child(auth.uid).val() === true",
        ".write": "data.child('participantsUid').child(auth.uid).val() === true"
      }
    },
    "messages": {
      "$chatRoomId": {
        ".read": "root.child('chatRooms').child($chatRoomId).child('participantsUid').child(auth.uid).val() === true",
        ".write": "root.child('chatRooms').child($chatRoomId).child('participantsUid').child(auth.uid).val() === true"
      }
    }
  }
}
~

현재 로그인한 유저가 속한 채팅방에서만 읽고 쓰게 콘솔에서 설정을 해줄 수 있다.

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read: if true;
      allow write: if request.auth.uid != null;
    }
  }
}

파이어스토어 같은경우는 읽는건 누구나 가능하지만, 작성하는건 인증된 사용자만 작성이 가능하게 했다.

색인

색인 같은경우, 데이터를 서버에서 받아올때 정렬된 상태로 받고 싶으면 색인 규칙을 추가하고 받아와야 한다.

    override suspend fun getRecentPost(count: Int, groupType: GroupType?): List<PostEntity> {
        var query = firebaseFirestore.collection(DataBaseType.POST.title)
            .orderBy("registeredDate", com.google.firebase.firestore.Query.Direction.DESCENDING)
            .limit(count.toLong())

        if (groupType != null) {
            query = query.whereEqualTo("groupType", groupType.name)
        }

        return query.get().await().documents.mapNotNull { snapshot ->
            snapshot.toObject(PostEntity::class.java)
        }
    }

다음은 등록된 날자를 기준으로 정렬해서 원하는 수 만큼의 데이터를 가져오는 코드이다.

코드 상으로 문제가 없었는데 아무리 해도 데이터가 오지 않았다.

알고보니까 콘솔에서 색인규칙을 추가하지 않아서 데이터를 가지고 올수 없었다.

콘솔에 들어가면 색인을 추가 할 수 있는데, 여기서 필드를 설정하고 정렬방식을 설정해준다.

여기서 registeredDate를 내림차순으로 설정하면 데이터를 불러올수 있다.

한참동안 고민하면 대부분 범인은 콘솔 이녀석이다.

내 코드를 의심하지 말아야겠다.

0개의 댓글