how to get a document from firestore using a function in typescript?

Viewed 1925

I wanted to get user information from my collection using their ID to send them notifications. This are my functions in index.ts

export const sendNotifications = functions.firestore
.document('messages/{groupId1}/{groupId2}/{message}')
.onCreate((snapshot, context) =>{
    console.log('Starting sendNotification Function');   
    const doc = snapshot.data();
    console.log(doc.content);
    console.log(getUserData(doc.idFrom))
    return true;
});

export async function getUserData(id: string){
    try {
        const snapshot = await admin.firestore().collection('users').doc(id).get();
        const userData = snapshot.data();
        if(userData){
            return userData.nickname;
        }       

    } catch (error) {        
        console.log('Error getting User Information:', error);
        return `NOT FOUND: ${error}`
    }
 }

From my deploy, I get the console log messages, the 'Starting sendNotification Function', then the actual 'doc.content' then an error for my 'getUserData(doc.idFrom)'.

Promise {
  <pending>,
  domain: 
   Domain {
     domain: null,
     _events: { error: [Function] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] } } 

Thank you in advance!

1 Answers

You should call your async getUserData() function with await.

The following should do the trick (untested):

export const sendNotifications = functions.firestore
  .document('messages/{groupId1}/{groupId2}/{message}')
  .onCreate(async (snapshot, context) => {
    try {
      console.log('Starting sendNotification Function');
      const doc = snapshot.data();
      console.log(doc.content);

      const nickname = await getUserData(doc.idFrom);
      // Do something with the nickname value
      return true;
    } catch (error) {
      // ...
    }
  });

async function getUserData(id: string) {
  try {
    const snapshot = await admin.firestore().collection('users').doc(id).get();
    if (snapshot.exists) {
       const userData = snapshot.data();
       return userData.nickname;
    } else {
      //Throw an error
    }
  } catch (error) {
    // I would suggest you throw an error
    console.log('Error getting User Information:', error);
    return `NOT FOUND: ${error}`;
  }
}

Or, if you don't want to have the Cloud Function async, you can do as follows:

export const sendNotifications = functions.firestore
  .document('messages/{groupId1}/{groupId2}/{message}')
  .onCreate((snapshot, context) => {
    console.log('Starting sendNotification Function');
    const doc = snapshot.data();
    console.log(doc.content);

    return getUserData(doc.idFrom)
      .then((nickname) => {
        // Do something with the nickname value
        return true;
      })
      .catch((error) => {
        console.log(error);
        return true;
      });
  });
Related