【问题标题】:Call external API with Cloud Function and create document使用 Cloud Function 调用外部 API 并创建文档
【发布时间】:2020-03-31 02:03:46
【问题描述】:

我正在尝试创建一些云功能来:

  1. 使用 Axios 调用 Google Directions API
  2. 根据 API 结果在 Firestore 创建文档
  3. 将文档引用返回给我的 iOS 应用程序。 (我使用 Blaze 计划,按需付费)

由于我的 Node / JS 知识非常基础,我无法创建以下函数。 有人可以快速看一下,让我知道我缺少什么吗?

观察: 该代码正在部署到 Firebase,没有任何警告和错误。我很确定问题出在我试图返回回调的方式上。

提前致谢

编辑

我对代码进行了一些更改,但我的 iOS 应用程序仍然收到 nil。 该代码仍未在 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"))
        })
  }

【问题讨论】:

    标签: node.js firebase google-cloud-firestore google-cloud-functions google-maps-sdk-ios


    【解决方案1】:

    我不知道这是否是最终解决方案,但是代码中有错误:

    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 语句中不会考虑。我试图测试它,但我所有的尝试都以这个错误结束。也许这个错误出现在您的日志中。

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      对于 HTTPS 触发器,您需要 return {status: 'OK', code: 200, data: json}

      这样它实际上会通过网络服务器响应。

      【讨论】:

      • Hey Martin,OP 似乎正在创建一个HTTPs Callable endpoint,您只需返回 JSON 数据即可返回给调用者。
      • 嘿,马丁和弗兰克,我尝试编辑代码并根据示例和您的答案进行了一些更改,但我仍然无法弄清楚发生了什么。我收到来自我的 iOS 应用程序的回调 nil 并且代码仍未在 firestore 上创建文档。
      • 我刚刚看了看;这必须是data 而不是message,正如documentation 显示的那样......这样客户端就会收到它期望的格式。
      猜你喜欢
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 2018-04-30
      • 2018-12-18
      • 2022-11-18
      • 2018-08-13
      相关资源
      最近更新 更多