2

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?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
StuartM
  • 6,743
  • 18
  • 84
  • 160

1 Answers1

3

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:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks @Frank, Good to know. I guess the other alternative is have the user manually enter a roomname and keep that as the doc ID. – StuartM Jan 12 '19 at 15:22
  • Definitely. But you'd need a roundtrip there too to check if the name they entered is still available. That's why the default IDs are so "chaotic": they are generated in the clients and are statistically guaranteed to be unique, which means that they can also work while the client is offline. – Frank van Puffelen Jan 12 '19 at 15:39