Firebase UID output to document with typescript cloud function

190 views
Skip to first unread message

Nathan Jones

unread,
Dec 17, 2020, 5:14:33 AM12/17/20
to Firebase Google Group
Hello, I'm new to both programming and Flutter but I'm starting to get my head around it. I am trying to put together an app that combines user and location information via Firebase so that I can show multiple user locations on a map. What I need help with and would like to do is write the Firebase UID and user location to the same Firestore document via a Typescript cloud function.

I've been working with this flutter Firebase background location plugin for several months and have figured out a lot about how it works. Concurrently I've been trying multiple Firebase Auth templates and have learned a fair amount about what API options are available. Most importantly I understand that the UID is the key value to identify my users.

I've also learned a fair amount about Firebase cloud functions and how to write specific data to a Firestore collection. I've learned how to write the user information and UID to a collection with a Javascript cloud function and I've also learned how to write the location information (lat, lng, etc...) to a collection via a Typescript cloud function.

My working Typescript is below, it has the location data I need. Can I modify the Typescript to include information such as UID or perhaps email address sourced from user data stored in Firebase?  Thanks for reading and for any suggestions on how to proceed. Nathan

import * as functions from 'firebase-functions';

exports.createLocation = functions.firestore
  .document('locations/{locationId}')
  .onCreate((snap, context) => {
    const record = snap.data();

    const location = record.location;

    console.log('[data] - ', record);

    return snap.ref.set({
      uuid: location.uuid,
      timestamp: location.timestamp,
      is_moving: location.is_moving,
      latitude: location.coords.latitude,
      longitude: location.coords.longitude,
      speed: location.coords.speed,
      heading: location.coords.heading,
      altitude: location.coords.altitude,
      event: location.event,
      battery_is_charging: location.battery.is_charging,
      battery_level: location.battery.level,
      activity_type: location.activity.type,
      activity_confidence: location.activity.confidence,
      extras: location.extras,
    });
});

Sam Stern

unread,
Dec 17, 2020, 8:15:20 AM12/17/20
to Firebase Google Group
Hi Nathan,

Firestore function triggers don't include information about who triggered them, only what data changed. So if you need to add something like the user's UID or email address you'll need to fetch that separately within the function (using the Firebase Admin SDK) or include it in the original document write from the client.

- Sam


--
You received this message because you are subscribed to the Google Groups "Firebase Google Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebase-tal...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/firebase-talk/bd8b2d07-878e-4d3a-83f9-1772cc76d593n%40googlegroups.com.

Kato Richardson

unread,
Dec 17, 2020, 11:39:06 AM12/17/20
to Firebase Google Group

Jorge Vergara

unread,
Dec 17, 2020, 5:38:47 PM12/17/20
to Firebase Google Group
Hey Sam,

Correct me if I'm wrong, but firestore triggers don't have both the snap/change AND the context? The context carries an auth property that has the user's uid and token: https://firebase.google.com/docs/reference/functions/cloud_functions_.eventcontext#properties_1.




--
Jorge Vergara

Nathan Jones

unread,
Dec 18, 2020, 6:43:26 AM12/18/20
to Firebase Google Group
Sam, fetching it with the admin sdk sounds easy enough, though I would not know off hand where to start to add that to the Typescript code I posted initially, any suggestions there?

Sam Stern

unread,
Dec 21, 2020, 6:13:27 AM12/21/20
to Firebase Google Group
@Nathan this page documents the Admin Auth SDK, specifically here's how you can fetch a user by UID:
https://firebase.google.com/docs/auth/admin/manage-users

In your code if you make your callback "async" you can make this really simple with async/await. Since you're new to TypeScript I'll give you a basic example, bold parts are new.

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp():

exports.createLocation = functions.firestore
  .document('locations/{locationId}')
  .onCreate(async (snap, context) => {
        
    // Fetch a user
    // See the UserRecord reference doc for the contents of userRecord.
    const userRecord = await admin.auth().getUser(uid)
    console.log(`Successfully fetched user data: ${userRecord.toJSON()}`);

    //... your other code here
});



Sam Stern

unread,
Dec 21, 2020, 6:14:35 AM12/21/20
to Firebase Google Group
Hi Jorge,

As mentioned in the documentation you linked:
"This field is only populated for Realtime Database triggers and Callable functions. For an unauthenticated user, this field is null. For Firebase admin users and event types that do not provide user information, this field does not exist."

So for Cloud Firestore triggers context.auth will not be populated.

- Sam

Reply all
Reply to author
Forward
0 new messages