Hi Auth0. When we have an async rule, can it run in the background?
My objective is track when users log-in, and therefore write to our Mongo database. The rule currently looks something like this, and waits for the mongodb write operation to complete:
function (user, context, callback) {
user.app_metadata = user.app_metadata || {};
const { MongoClient } = require("mongodb@3.1.4");
const uri = `mongodb+srv://${dbUser}:${dbPwd}@${dbHost}/admin?retryWrites=true`;
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
if (err) return callback(err);
const collection = client.db(dbName).collection(colName);
collection.insert({ // some data })
.then(() => {
client.close();
callback(null);
})
.catch((err) => callback(err));
});
}
To improve performance, can we write the rule so we don’t await the write?
Would something like this work ok - or do I miss something here?
function (user, context, callback) {
user.app_metadata = user.app_metadata || {};
const { MongoClient } = require("mongodb@3.1.4");
const uri = `mongodb+srv://${dbUser}:${dbPwd}@${dbHost}/admin?retryWrites=true`;
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
if (err) {
// Log error somewhere - maybe to Auth0 logs?
};
const collection = client.db(dbName).collection(colName);
collection.insert({ // some data })
.then(() => {
client.close();
})
.catch((err) => {
// Log error somewhere - maybe to Auth0 logs?
});
});
// Callback before connect and write operation is done. Is this ok?
callback(null, user, context);
}
Thanks for your help.
Update
After some googling, I found this sample rule from Auth0 “Record or update an Intercom User”. And this rule specifically does not wait for the operation to complete, but calls the callback straight away - so that answers part of the question