繁体   English   中英

Firebase 云功能 - 通过提供的字段名称获取文档

[英]Firebase cloud function - get documentby provided field name

当我的客户调用https://us-central1-myapp.cloudfunctions.net/getWebsiteIdByName/mywebsite 时,我希望调用以下 firebase 函数并返回具有匹配名称的文档。 我已经编写了下面的函数,但不断收到错误: Error: could not handle the request 我怎样才能解决这个问题? 我的代码如下:

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

exports.getWebsiteIdByName = functions.https.onRequest((req: any, res: any) => {
  let websiteName = req.url.split("/");
  websiteName = websiteName[websiteName.length - 1];
  res.set('Access-Control-Allow-Origin', '*');
  const website = admin.firestore().collection('websites', (ref: any) => ref.where('name', '==', websiteName).limit(1)).get();
  return website.then(function (response: any) {
    if (response[0].data()) {
      res.end(`{ "websiteId": "${response[0].data()['id']}" }`);
    } else {
      res.end(`{ "websiteId": null }`);
    }
    console.log('Request successful!');
  }).catch((error: any) => console.log('Request failed: ', error));
});

尝试 2

exports.getWebsiteIdByName = functions.https.onRequest((req: any, res: any) => {
  let websiteName = req.url.split("/");
  websiteName = websiteName[websiteName.length - 1];
  res.set('Access-Control-Allow-Origin', '*');
  const website = admin.firestore().collection('websites', (ref: any) => ref.where('name', '==', websiteName).limit(1)).get();
  return website.then(function (response: any) {
    if(response.empty) {
      res.end(`{ "websiteName": null }`);
    } else {
      res.end(`{ "websiteName": ${JSON.stringify(response.docs[0].get())}`);
    }
    console.log('Request successful!');
  }).catch((error: any) => console.log('Request failed: ', error));
});

最终想通了,我返回了一个 QuerySnapshot,所以它必须以不同的方式处理。

exports.getWebsiteIdByName = functions.https.onRequest((req: any, res: any) => {
  let websiteName = req.url.split("/");
  websiteName = websiteName[websiteName.length - 1];
  res.set('Access-Control-Allow-Origin', '*');
  const website = admin.firestore().collection('websites', (ref: any) => ref.where('name', '==', websiteName).limit(1)).get();
  return website.then(function (response: any) {
    if (response.empty) {
      res.end(`{ "websiteId": null }`);
    } else {
      res.end(`{ "websiteId": ${JSON.stringify(response.docs[0].data()['id'])} }`);
    }
    console.log('Request successful!');
  }).catch((error: any) => console.log('Request failed: ', error));
});

暂无
暂无

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

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