简体   繁体   English

Firebase 云功能:更新用户个人资料

[英]Firebase cloud functions: Update user profile

In my e-commerce project, I want to use google maps api to insert user's shop location.在我的电子商务项目中,我想使用 google maps api 插入用户的商店位置。

I used google cloud functions to insert the latitude, the longitude, and the address.我使用谷歌云函数插入纬度、经度和地址。

Now I could insert the data in the collection called locations.现在我可以在名为locations的集合中插入数据。 But I want to attach those information to the user profile collection.但我想将这些信息附加到用户配置文件集合中。

So how can I insert latitude, longitude, and user address into the user profile collection?那么如何将纬度、经度和用户地址插入到用户配置文件集合中呢?

This is my index.js这是我的 index.js

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const Firestore = admin.firestore;
const db = Firestore();

const axios = require("axios");
const cors = require("cors")({
    origin: true
});

const googleMapsApiKey = "AIzaSyAnp23T2tbYj9Ho8uYmcE6W4KnbvZKlEjc";

exports.geocodeAddressAndSave = functions.https.onRequest(async (request, response) => {
    try {
        let address = encodeURI(request.body.address);
        let { data } = await axios.get(
            `https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=${googleMapsApiKey}`
        );

        if (data.status !== "OK") {
            //no results
            return cors(request, response, () => {
                response.status(200).send("No Results");
            });
        }

        const geocodedLocation = data.results[0];
        const objGeolocation = {
            address: geocodedLocation.formatted_address,
            geoPoint: new admin.firestore.GeoPoint(geocodedLocation.geometry.location.lat, geocodedLocation.geometry.location.lng)
        }

        //firebase

        await 

        db.collection('locations').add(objGeolocation);

        return cors(request, response, () => {
            response.status(200).send(objGeolocation);
        });
    } catch (error) {
        return cors(request, response, () => {
            console.log(error);
            response.status(500).send();
        });
    }
});

Vue.js Vue.js

 <template>
  <div id="app" class="container mt-5">
    <b-form @submit.prevent="handleFormSubmit">
      <b-row>
        <b-col md="6">
          <b-form-group label="Street">
            <b-form-input v-model="formData.street"></b-form-input>
          </b-form-group>
        </b-col>
      </b-row>

      <b-row>
        <b-col md="3">
          <b-form-group label="City">
            <b-form-input v-model="formData.city"></b-form-input>
          </b-form-group>
        </b-col>
        <b-col md="3">
          <b-form-group label="State">
            <b-form-input v-model="formData.state"></b-form-input>
          </b-form-group>
        </b-col>
        <b-col md="3">
          <b-form-group label="Zip">
            <b-form-input v-model="formData.zip"></b-form-input>
          </b-form-group>
        </b-col>
      </b-row>
      <b-button type="submit" variant="primary">Submit</b-button>
    </b-form>

    <GmapMap
      :center="{lat:13.756331, lng:100.501762}"
      :zoom="4"
      map-type-id="roadmap"
      style="width: 100%; height: 500px; margin-top:60px;"
    >
       <div>
            <GmapMarker
            :clickable="true"
            @draggable="true"
            @click="center=m.position"
        />
    </div>
    </GmapMap>
  </div>
</template>

<script>
import axios from 'axios';
// firestore
import fireApp from '@/plugins/firebase'
const firebase = require("firebase");
require("firebase/firestore");
const db = firebase.firestore();
let id = String(id);

export default {
  name: "MapFirestore",
  data: () => ({
    savedLocations: [],
    formData: {
      street: "",
      city: "",
      state: "",
      zip: "",
    },
  }),
  
  firestore(){
      const user = fireApp.auth().currentUser;
      return {
        formData: db.collection('Profile').doc(user.uid),
      }
  },
  methods: {
    async handleFormSubmit() {
      //validate form
      if (
        !this.formData.street ||
        !this.formData.city ||
        !this.formData.state ||
        !this.formData.zip
      ) {
        alert("You must add a full address!");
        return;
      }

      //Make request
      let address = `${this.formData.street}, ${this.formData.city}, ${this.formData.state} ${this.formData.zip}`;
      let { data } = await axios.post(
        "https://us-central1-geocodeing-58a86.cloudfunctions.net/geocodeAddressAndSave",
        {
          address: address,
        }
      );

      if (data === "No Results") {
        alert("No results for address");
        return;
      }

      //massage data to fit our schema
      let obj = {
        address: data.address,
        geoPoint: {
          latitude: data.geoPoint._latitude,
          longitude: data.geoPoint._longitude,
        },
      };

      //add to saved locations to update map
      this.savedLocations.push(obj);

      //clear form
      this.formData.street = "";
      this.formData.city = "";
      this.formData.state = "";
      this.formData.zip = "";
    },
  },
};
</script>

I want to insert the data into this collection called Profile.我想将数据插入到这个名为 Profile 的集合中。 在此处输入图片说明 我的用户个人资料集合。

You'll need to know the UID of the user, and then update the user profile with that.您需要知道用户的 UID,然后用它更新用户配置文件。 If this is a secure operation (it likely is), you'll need to pass the UID in a secure way.如果这是一个安全操作(很可能是),您需要以安全的方式传递 UID。 See: Getting user info from request to Cloud Function in Firebase请参阅: 从 Firebase 中的 Cloud Function 请求获取用户信息

Once you have the UID, you can update the profile document with something like:获得 UID 后,您可以使用以下内容更新配置文件:

db.collection('profiles').doc(uid).update({ ... });

I changed my vue code.我更改了我的 vue 代码。

var user = firebase.auth().currentUser;

      db.collection('Profile').doc(user.uid).update({ 
            address: data.address,
            latitude: data.geoPoint._latitude,
            longitude: data.geoPoint._longitude,
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM