Home > Mobile >  Firebase function exception when onCall Http
Firebase function exception when onCall Http

Time:12-19

com.google.firebase.functions.FirebaseFunctionsException: Response is not valid JSON object.

    exports.loadVideos = functions
  .region('asia-south1')
  .https.onRequest(async (req, res) => {
    let uid = []

    const subscribers = await db
      .collection(SUBSCRIPTIONS_COLLECTION)
      .doc('05piDSvu5mNxHOn2yKpnL2V322r1')
      .get()
    subscribers.data().subsBy.forEach((s) => {
      uid.push(s.userId)
    })

    return db
      .collection('videos')
      .where('userId', 'not-in', uid)
      .get()
      .then((snapshot) => {
        if (snapshot.empty) {
          return res.status(404).send({
            error: 'Unable to find the document',
          })
        }
        let items = []
        snapshot.docs.forEach((doc) => {
          items.push(doc.data())
        })
        return res.status(200).send(items)
      })
      .catch((err) => {
        console.error(err)
        return res.status(404).send({
          error: 'Unable to retrieve the document',
          err,
        })
      })
  })

Unable to find out issue, it's working well when trying with single text but I need whole collection.

CodePudding user response:

Callable Cloud Functions can only return JSON types. You can't return an entire QuerySnapshot, which is what your code is trying to do.

If you want to return the data of the documents, that'd be:

return { videos: filteredVideo.map((doc) => doc.data()) }

If you also want to return the document ID of each document, that'd be:

const result = filteredVideo.map((doc) => {
  return { id: doc.id, data: doc.data() }
})
return { videos: result }

CodePudding user response:

If u send items array in response directly, it will throw Exception.

There are some rules ref Medium Article to follow.

As of Exception, there is no valid JSON object. You have to convert your items array to an Object and pass in response followed by key "data" :

Wrong return res.status(200).send(items)

Right return res.status(200).send({ data: { items } })

  • Related