Currently, I am in the process of creating a Firebase cloud function (using Express) that performs the following tasks: - Checking if a user exists in the database. - Sending a message to the Telegram API based on whether the user exists or not.
The problem arises when attempting to execute the function. While Firebase logs successfully display the console.log indicating whether the user exists, the message fails to send to Telegram. The error log states:
[2020-02-15T10:41:34.568Z] @firebase/database: FIREBASE WARNING: Exception was thrown by use callback. Error: Can't set headers after they are sent. at validateHeader (_http_outgoing.js:491:11) at ServerResponse.setHeader (_http_outgoing.js:498:3) at ServerResponse.header (/srv/node_modules/express/lib/response.js:771:10) at ServerResponse.send (/srv/node_modules/express/lib/response.js:170:12) at ServerResponse.json (/srv/node_modules/express/lib/response.js:267:15) at ServerResponse.send (/srv/node_modules/express/lib/response.js:158:21) at firebase.database.ref.child.once.snapshot (/srv/index.js:59:40) at onceCallback (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:4933:51) at /srv/node_modules/@firebase/database/dist/index.node.cjs.js:4549:22 at exceptionGuard (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:698:9)
I would greatly appreciate any assistance provided. Thank you!
app.post("/", async (req, res) => {
const isTelegramMessage =
req.body &&
req.body.message &&
req.body.message.chat &&
req.body.message.chat.id &&
req.body.message.from &&
req.body.message.from.first_name &&
req.body.update_id;
const user_id = req.body.message.from.id
firebase.initializeApp(firebaseConfig);
let myUser;
const chat_id = req.body.message.chat.id;
const {
first_name
} = req.body.message.from;
// Check User Exists
firebase
.database()
.ref("/telegramUsers")
.child(req.body.message.from.id)
.once("value", snapshot => {
if (snapshot.exists()) {
myUser = true;
console.log("exists!", myUser);
return res.status(200).send({
method: "sendMessage",
chat_id,
text: `Welcome Back ${first_name}`
});
} else {
myUser = false;
console.log("does not exist!");
return res.status(200).send({
method: "sendMessage",
chat_id,
text: `Hello ${first_name}`
});
}
});
return res.status(200).send({
status: "not a telegram message"
});
});