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

Time:09-29

I have a Webhook that delivers a complex JSON payload to my Cloud Function URL, and writes that JSON to collections & documents within my Cloud Firestore.

My Cloud Function looks something like:

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

This works when its a simple JSON, for example: one that isn't heavily nested.

What I don't understand, is how to format this Node.JS Google Cloud Function to accept a field from a complex JSON that is nested.

I believe the Node.JS Runtime on Google Cloud Functions uses the Express Middleware HTTP framework.

Sample JSON:

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

I know how to return the id in line 1. I'm unsure how to return the id in line 3.

CodePudding user response:

If you want add whole webhook payload as it is then you can just pass that object in 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()
);

If you want a specific (e.g. id in provided JSON) you can access that like this:

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()
);

A Firestore document is like a JSON object so you can keep nesting maps that way upto a maximum depth of 20.

  • Related