Skip to content

Instantly share code, notes, and snippets.

@raibima
Last active July 30, 2021 03:28
Show Gist options
  • Select an option

  • Save raibima/367169d700839570e339541e7275f939 to your computer and use it in GitHub Desktop.

Select an option

Save raibima/367169d700839570e339541e7275f939 to your computer and use it in GitHub Desktop.

Need to implement two interfaces:

  • function subscribeChatRoom(orderId, onMessage)
  • function sendMessage(orderId, message)

Message Schema

Message:

  • id (string)
  • created_at (timestamp)
  • message: (string)
  • sender_id: (string)

These messages will be stored inside the orders collection. Specifically, each order document in the collection will have a subcollection called chat.

Collection path: orders > order ID > chat > message ID.

Subscription

To set up the subscription, get the firebase collection ref and attach an onSnapshot listener.

import firestore from '@react-native-firebase/firestore';

const COLLECTION_NAME = 'orders';
const SUBCOLLECTION_NAME = 'chat';

// add this to the implementation of
// subscribeChatRoom
const db = firestore();
const chatRef = db.collection(`${COLLECTION_NAME}/${orderId}/${SUBCOLLECTION_NAME}`);
chatRef.onSnapshot(snapshot => {
  // do something on collection change (add / remove docs)
  const docs = snapshot.docs;
  
  // call onMessage
});

Message Sending

To send message, you simply add a new doc to the subcollection

import firestore from '@react-native-firebase/firestore';
import {getCurrentUser} from '~/services/user';

const COLLECTION_NAME = 'orders';
const SUBCOLLECTION_NAME = 'chat';

// add this inside the sendMessage implementation
const db = firestore();
const chatRef = db.collection(`${COLLECTION_NAME}/${orderId}/${SUBCOLLECTION_NAME}`);
chatRef
  .doc() // creates a new doc, let the SDK generates the ID
  .set({
    created_at: new Date(),
    message: 'my message',
    sender_id: getCurrentUser().uid,
  });

Learn more

https://github.com/jagocoffee/jago-consumer-app/pull/28

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment