Episode 5. FirebaseService.

Now we are going to create your main class to do communication with Firebase application.

Lets define our collections in /constants/collections.js :

export default {

MESSAGES: 'messages'

}

And lets export it in /constants/index.js for easy access:

export COLLECTIONS from './collections'

Now we are ready to implement FirebaseService.js :

import firebase from 'react-native-firebase'

import { COLLECTIONS } from '../constants'



export default class FirebaseService {

auth = firebase.auth()



firestore = firebase.firestore()



messageRef = this.firestore.collection(COLLECTIONS.MESSAGES);



async signIn () {

try {

const response = await this.auth.signInAnonymously()

return { user: response.user }

} catch (error) {

return { error }

}

}



async fetchMessages () {

const messages = await this.messageRef

.orderBy('created_at', 'desc')

.limit(10)

.get()



return messages.docs

}



async createMessage ({ message, uid }) {

await this.messageRef.add({

message,

user_id: uid,

created_at: new Date()

})

}

}

Lets walk through the code:

auth = firebase.auth() and firestore = firebase.firestore() even if Firebase library under the hood cache auth() and firestore() initialized instance I preferably still save instance to the variable, just in case.

messageRef = this.firestore.collection(COLLECTIONS.MESSAGES) since we will have only one collection, I cache path to collection, just to avoid calling each time a query builer.

signIn — perhaps in your application you will not required sign in, since, probably, in real project you will have your own authorization. In this case I just do anonymous authorization, just to get unique UID of the user, to identify user in Firebase collection.

fetchMessages — function to fetch last 10 message in specific order. We need this order to have a proper position of messages in our chat. We limit our messages to 10 for two purposes:

We will use this as our initial load We just insure, the we will fetch new messages and filter old one, just in case web-sockets did not deliver some messages (yes, under the hood Firebase use web-sockets to do server to client communication).

createMessage — function to create message. Notice, I use UID what I retrieved with Firebase sign-in method, this will be a good case for you, if you have real backend to use user_id of your database, and your strange backend guy had an access to user messages from backend.

Now lets export our class and don’t forget to initialize a new instance of our FirebaseService class: