我想做的事:
我对云功能的工作方式相当陌生,只需要帮助了解我做错了什么。
需要从 firestore 请求位置以通过 firebase 云功能对本机客户端做出反应。
我在客户端尝试了类似的方法,但在使用云功能发出请求时需要获得相同的结果。
客户端代码:
import firebase from 'react-native-firebase';
const lat = 45.78768768
const lng = -67.56457667
const httpsCallable = firebase.functions().httpsCallable('findLocations');
let collection = this.props.navigation.state.params.document; //collection name eg hotels
const test = {
db: collection.name,
coordinates: {
latitude: lat,
longitude:lng
}
}
httpsCallable({
request: test })
.then(({ data }) => {
console.long(data);
this.setState({ data: data });
})
.catch((httpsError) => {
console.log(httpsError.code); // invalid-argument
console.log(httpsError.message); // Your error message goes here
});
云功能:
const admin = require('./node_modules/firebase-admin');
const firebase = require('./node_modules/firebase');
const { GeoCollectionReference, GeoFirestore, GeoQuery, GeoQuerySnapshot } = require('./node_modules/geofirestore');
const serviceAccount = require('./serviceAccount.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'app-url',
});
const firestore = admin.firestore();
const geofirestore = new GeoFirestore(firestore);
const settings = { timestampsInSnapshots: true };
firestore.settings(settings);
exports.findLocations = functions.https.onCall((data) => {
if (!data.request) {
throw new functions.https.HttpsError(
'invalid-argument', // code
'Your error message goes here', // message
);
} else {
let locations = [];
const geocollection = geofirestore.collection(data.db);
geocollection
.limit(20)
.near({
center: new firebase.firestore.GeoPoint(data.latitude, data.longitude),
radius: 100,
})
.get()
.then((GeoQuerySnapshot) => {
GeoQuerySnapshot.docs.forEach((doc) => {
return locations.push(doc.data());
});
})
.catch(function(error) {
console.log('Error getting documents: ', error);
});
}
return { locations: locations };
});