Compute a unique ID with JavaScript

Hello Bubble Community,

I am currently working on a feature that requires computing a unique identifier based on user IDs, and I’m struggling to accomplish the following steps in Bubble using JavaScript. This approach is based on the steps outlined in the TalkJS documentation.

  1. Take two ids of users and put them in an array
  2. Sort them lexicographically
  3. JSON encode them
  4. Hash the result using SHA1, return the first 20 characters

In pseudocode, the function looks like this:

var sorted = [me.id, other.id].sort()
    var encoded = JSON.encode(sorted)
    var hash = sha1(encoded) // as lowercase hex
    return truncate(hash, 20)

How can I do this in Bubble?

This is the code I want to run:

function computeConversationId(user1Id, user2Id) {
    // Step 1: Put the user IDs in an array
    const userIds = [user1Id, user2Id];

    // Step 2: Sort them lexicographically
    userIds.sort();

    // Step 3: JSON encode them
    const userIdsJson = JSON.stringify(userIds);

    // Step 4: Hash the result using SHA1 and return the first 20 characters
    const sha1Hash = crypto.createHash('sha1').update(userIdsJson).digest('hex');
    const conversationId = sha1Hash.slice(0, 20);

    return conversationId;
}

// Example usage
const user1Id = 'a';
const user2Id = 'b';
const conversationId = computeConversationId(user1Id, user2Id);
console.log(`Conversation ID: ${conversationId}`);

Thank you in advance!

This topic was automatically closed after 70 days. New replies are no longer allowed.