2
votes

We are using Firebase Firestore for data storage. When a user creates a new room, we want the reference to be easy to remember so that a user can share the room ID/code with other users.

At present Firestore will create a unique reference such as: DvfTMYED5cWdo5qIraZg

This is too long and difficult to remember or share. We could set a different reference manually, but they have to be unique. The other point is that users can create multiple rooms so the reference would have to change each time.

Is there a way to use shorter/better references for this use case?

1

1 Answers

3
votes

Firebase/Firestore has nothing built in for shorter references, as they wouldn't have enough entropy to statistically guarantee uniqueness. But since creating chat rooms is likely a fairly low-volume operation, you can implement this in your app by:

  1. Generating your own token for each room, for example a counter.
  2. Checking in the database whether this room is available.
  3. If the token is already taken, generate another one and try again.

This is pretty much how auto-increment fields work on most databases. On Firestore you'd create a document where you keep the current counter value:

chat_rooms (collection)
  COUNTERS: { last_room_id: 2 } (document)
  chatroom_1: { room_id: 1, name: "Chat room for Stuart and Frank" } (document)
  chatroom_2: { room_id: 2, name: "Public chat room" } (document)

When you now create a new room, you:

  1. Start a transaction.
  2. Read COUNTERS.
  3. Read the last_room_id, and increment it.
  4. Write the updated document back.
  5. Create a new document for the new chat room.
  6. Commit the transaction

Note that there are many ways to generate the codes. The counter approach above is a simple one, but I recommend checking out more options. Some interesting reading: