Error: Response is not valid JSON object on firebase function with onCall

Viewed 697

Here is my cloud function code

 exports.markThemAllRead = functions.https.onCall((data) => {
    const user = {
        id: data.id,
    }
    let batch = admin.firestore().batch();

    admin.firestore().collection("Notifications").doc("comments").collection(user.id).get().then(querySnapshot => {
        if(querySnapshot.empty){
            return "nice"
        }else {
            querySnapshot.forEach(doc=>{
                batch.update(doc.ref, {isRead:true})
            });
            return batch.commit()
        }
    }).catch(err => {
        console.log(err)
    })
    return "Good"
    })

I tried many combinations of return statements, but I keep getting Error: Response is not valid JSON object. Can anyone guide me through what could the issue be? I have many other working onCall functions in my code, but this is one is the only one with the batch.update()... perhaps that has something to do with it?

EDIT ATTEMPT

Still getting the same error when trying this:

exports.markThemAllRead = functions.https.onCall((data) => {
    const user = {
        id: data.id,
    }

    return markThemRead(user)

})

async function markThemRead(user){
    let batch = admin.firestore().batch();

    const docsRef = admin.firestore().collection("Notifications").doc("comments").collection(user.id)

    const docs = await docsRef.get();

    docs.forEach(function(doc){
        batch.update(doc.ref, {isRead:true})
    })

    return batch.commit()

}
1 Answers

Based on the example of in the Firebase documentation Sync, async and promises

async function markThemRead(user){
    let batch = admin.firestore().batch();

    const docsRef = admin.firestore().collection("Notifications").doc("comments").collection(user.id)

    const docs = await docsRef.get();

    docs.forEach(function(doc){
        await batch.update(doc.ref, {isRead:true})
    })

    return batch.commit().then(function () { return {status: "All Good"}})

}
Related