Reputation: 335
I am trying to terminate my functions when some conditions are met. but it looks like function ends but the control is going beyond response.send and failing with exception "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client"
Why it is not existing when "res.status(400).send" and what is required to exit?
export const getAssessment = functions.https.onRequest(async (req, res) => {
return cors(req, res, async () => {
console.log("getAssessment - start");
const data = req.body;
const db_fs = admin.firestore();
const userId = data.userId;
const bookingDocId = data.bookingDocId;
console.log("userId " + userId + " bookingDocId " + bookingDocId);
if (!userId || !bookingDocId) {
console.error("'userId or bookingDocId is missing");
return res.status(400).send({ message: 'userId or bookingDocId is missing' });
}
var bookingRef = await db_fs
.collection("/bookings")
.doc(bookingDocId)
.get();
if (!bookingRef.exists) {
console.error('No document found with ' + bookingDocId);
return res.status(400).send({ message: 'No document found with ' + bookingDocId });
}
try {
var reportRef = db_fs.collection("/bookings/" + bookingDocId + "/reports");
var allReportSnapShot = await reportRef.get();
let reports = [];
allReportSnapShot.forEach(report => {
reports.push(report.data());
});
console.log("total reports " + reports.length);
console.log("getAssessment - end");
res.status(200).send(reports);
} catch (error) {
res.status(500).send({ message: 'failed', data: error });
}
})
});
Logs:
i functions: Beginning execution of "us-central1-getAssessment"
> getAssessment - start
! functions: The Cloud Firestore emulator is not running, so calls to Firestore will affect production.
> userId 34344 bookingDocId uMMItjSf7h5lAXcHqtL
> No document found with uMMItjSf7h5lAXcHqtL
i functions: Finished "us-central1-getAssessment" in ~1s
> total reports 0
> getAssessment - end
> (node:20560) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
> at ServerResponse.setHeader (_http_outgoing.js:561:11)
Upvotes: 2
Views: 329
Reputation: 6892
I am guessing here - but it looks like if the first conditionals were to be executed then you would send the response and the code would continue to run and send further responses.
Why don't you try set one res at the end, and use your conditionals to build the payload and see if that works?
Upvotes: 1