Async rule writing to a database on login, directly call callback?

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 :grinning:

Hi @alexab,

As you have discovered, rules do not run async. At this time, there is no hook (async action) for completing this type of request.

You can send the request and move on, like you have mentioned, or you could use a feature like log streaming to build this out manually via logs.

Hope this helps to clarify!

Hi Dan.

I am not sure I understand your answer?

If I configure this code to run:

function (user, context, callback) {
  var moment = require('moment-timezone');

  var data = { // Some data};
  var accessToken = 'YOUR INTERCOM ACCESS TOKEN';

  request.post({
    url: 'https://api.intercom.io/users',
    headers: {
      'Authorization': 'Bearer ' + accessToken,
      'Accept': 'application/json'
    },
    json: data
  }).catch(err => request.post({ // Will this code execute!? })
  callback(null, user, context);
}

I’m unsure if the above code in the catch(err) block will execute?

The log streaming sounds like the solution to this specific problem, but we are also working on other rules at the moment :nerd_face:

Now that I have you attention, would you happen to know the answer for this some-what related question?

Yes, the err function will execute, but the user will have to wait to be logged in until the callback function completes. This can eventually slow things down, since your application will not receive a token until after the rules are finished.

Sure let me take a look.

1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.