如何使用 Complex JSON Webhook 中的 Node JS Cloud Function 写入 Cloud Firestore?

How to write to the Cloud Firestore using Node JS Cloud Function from Complex JSON Webhook?

我有一个 Webhook,它向我的 Cloud Function URL 传送复杂的 JSON 负载,并将该 JSON 写入我的 Cloud Firestore 中的集合和文档。

我的云函数看起来像:

exports.webhook = functions.https.onRequest(async (req, res) => {
     await admin.firestore().collection("testCollection").doc().set({
          nameOfFieldFromFirestore: data.nameOfFieldFromJson,
]);

这在它是一个简单的 JSON 时有效,例如:没有大量嵌套的。

我不明白的是如何格式化此 Node.JS Google 云函数以接受来自嵌套的复杂 JSON 的字段。

我相信 Node.JS Cloud Functions 上的 Node.JS 运行时使用 Express 中间件 HTTP 框架。

样本JSON:

"id": "1",
"people": {
     "id": "1",
}

我知道如何 return 第 1 行中的 ID。我不确定如何 return 第 3 行中的 ID。

如果你想按原样添加整个 webhook 有效负载,那么你可以在 set():

中传递该对象
exports.webhook = functions.https.onRequest(async (req, res) => {
  const payload = req.body
 
  await admin.firestore().collection("testCollection").doc().set(payload)
  res.status(200).end()
);

如果您想要特定的(例如提供的 ID JSON),您可以像这样访问它:

exports.webhook = functions.https.onRequest(async (req, res) => {
  const payload = req.body

  await admin.firestore().collection("testCollection").doc().set({
    someField: payload.people.id
  })
  res.status(200).end()
);

Firestore 文档就像一个 JSON 对象,因此您可以将地图嵌套到 maximum depth of 20