我正在尝试创建一些云函数来:
- 使用Axios调用Google Directions API
- 根据API结果在Firestore创建文档
- 将文档引用返回到我的iOS应用程序。(我在Blaze计划中,现收现付(
我很难创建以下函数,因为我的Node/JS知识非常基础。有人能不能快速看一下,让我知道我缺了什么?
Obs.:代码正在部署到firebase,没有任何警告和错误。我确信问题出在我试图回拨电话的方式上。
提前感谢
编辑
我对代码做了一些更改,但我的iOS应用程序仍然没有收到任何更改。代码仍然没有在firestore上创建文档。
const functions = require('firebase-functions');
const axios = require('axios');
var admin = require("firebase-admin");
admin.initializeApp();
// Func called by iOS App, If user is auth, call google maps api and use response to create a document at firestore
exports.getDistanceAndSavePackage = functions.https.onCall((data, context) => {
if (!context.auth){ return {status: 'error', code: 401, message: 'Not signed in'} }
const userId = context.auth.uid;
const startCoordinates = data.startCoords;
const endCoordinates = data.endCoords;
const pkgDocReference = getGoogleRoute(startCoordinates, endCoordinates, res => {
console.log('google cloud function has returned');
let venueId = userId;
let distance = res.distance.value;
let resultStartAdd = res.start_address;
let resultEndAdd = res.end_address;
const pkgDocRef = createTempPackage(venueId, distance, resultStartAdd, resultEndAdd, resultPkg => {
return resultPkg
})
return pkgDocRef;
})
return pkgDocReference;
});
//Create Package Document
function createTempPackage(venueId, distance, startingAddress, endingAddress, callback){
console.log('Creating temp package');
const docRef = admin.firestore().doc(`/temp_packages/`)
docRef.set({
id: docRef.id,
venue_id: venueId,
distance: distance,
starting_address: startingAddress,
ending_address: endingAddress,
timestamp: admin.database.ServerValue.TIMESTAMP,
status: 0
})
.then(docRef => {
console.log('Doc created')
return callback(docRef);
}).catch(error => {
console.log('Error trying to create document')
return callback(error);
})
}
//Call Google directions API
function getGoogleRoute(startCoords, endCoords, callback){
axios({
method: 'GET',
url: 'https://maps.googleapis.com/maps/api/directions/json',
params: {
origin: startCoords,
destination: endCoords,
key: 'mykey'
},
})
.then(response => {
let legs = response.data.routes[0].legs[0];
return callback(legs);
})
.catch(error => {
console.log('Failed calling directions API');
return callback(new Error("Error getting google directions"))
})
}
我不知道这是否是最终解决方案,但代码中有一个错误:
const docRef = admin.firestore().doc('/temp_packages/')
此语句应更正错误:
Value for argument "documentPath" must point to a document, but was "${documentPath}". Your path does not contain an even number of components.
该错误在docRef.set
之前抛出,因此在catch
语句中不会将其考虑在内。我试着测试它,但我所有的尝试都以这个错误告终。也许这个错误在你的日志中。
我希望它会有所帮助!
对于HTTPS触发器,您需要return {status: 'OK', code: 200, data: json}
。
这样它就可以通过网络服务器进行响应。