Hi @JayaC-MSFT ,
I believe the network is not the issue in this case, but the TLS connection. The function is able to reach the DB but the connection is refused because apparently I need a certificate to connect to the mongoDB. I'm not using MongoDB Atlas, but Azure Cosmos DB with MongoAPI, so the links also didn't help in this case.
I decided to delete all the CosmosDB resources and use Azure SQL instead. In this case, it is working just fine. I had to adapt a bit the examples I found though, because the function is by default async and it needs some tweaks for working properly.
This is how it currently looks like:
// @ts-check
import { AzureFunction, Context, HttpRequest } from "@azure/functions"
import { Connection, Request, TYPES } from "tedious";
const httpTrigger: AzureFunction = function (context: Context, req: HttpRequest) {
context.log('HTTP trigger function processed a request.');
if (req.body && req.body.email) {
// Create connection to database
const config = {
authentication: {
options: {
userName: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD
},
type: "default"
},
server: process.env.DB_SERVER,
options: {
database: process.env.DB_NAME,
encrypt: true
}
};
const connection = new Connection(config);
// Attempt to connect and execute queries if connection goes through
connection.on("connect", err => {
if (err) {
context.log(err.message);
context.res = { status: 500 };
context.done();
} else {
// Read all rows from table
const request = new Request(
`BEGIN
IF NOT EXISTS (SELECT * FROM Subscriptions s
WHERE s.email = @email)
BEGIN
INSERT INTO Subscriptions (name, email)
VALUES (@name, @email)
END
END`,
(err, rowCount) => {
if (err) {
context.log(err.message);
context.res = { status: 500 };
} else {
context.log(`${rowCount} row(s) created`);
context.res = { status: 200 };
}
connection.close();
context.done();
}
);
request.addParameter('name', TYPES.NVarChar, req.body.name);
request.addParameter('email', TYPES.NVarChar, req.body.email);
request.on("row", columns => {
columns.forEach(column => {
console.log("%s\t%s", column.metadata.colName, column.value);
});
});
connection.execSql(request);
}
});
connection.connect();
}
else {
context.res = { status: 400 };
context.done();
}
};
export default httpTrigger;