Back

Function to generate Unique IDs. Rate my code quality please.

  • 0
  • Functions
Vincent Ca
24 May, 2023, 16:12

Hello ! Can you tell me if the function I wrote is well optimized or not ? It have to generate Unique ID like "AZ45DF" for documents when inserting. Thank you for your returns.

TypeScript
    const payload = JSON.parse(req.variables["APPWRITE_FUNCTION_EVENT_DATA"]);
    const {
        $id,
        $collectionId
    } = payload;

    if (!payload.hasOwnProperty("id")) return console.error("No ID attribute in this collection");

    let uniqueId = "";

    while (true) {
        for (let i = 0; i < 6; i++) {
            const randomIndex = Math.floor(Math.random() * characters.length);
            uniqueId += characters[randomIndex];
        }

        const idQuery = [
            sdk.Query.equal("id", uniqueId),
        ];
        const requestIds = await databases.listDocuments(
            req.variables["USERS_DATABASE_ID"],
            $collectionId,
            idQuery
        );
        const responseIds = requestIds.documents;
        if (responseIds.length === 0) {
            break;
        } else {
            uniqueId = ""
        }
    }
    const json = {
        id: uniqueId
    };
    await databases.updateDocument(req.variables["USERS_DATABASE_ID"], $collectionId, $id, json)
    res.json({
        success: true,
    });
}
TL;DR
The user needs help optimizing their function for generating unique IDs. They want to generate a 6-character ID for documents and ensure it is unique. They have provided a code snippet. The code iterates through a loop to generate a random 6-character ID. It then queries the database to check if the ID already exists. If it does, it generates a new ID and repeats the process. Once a unique ID is found, it updates the document with the ID and returns a success response. Some suggestions for optimization are: 1. Instead of using an infinite loop, use a `while` loop with a condition that can be fulfilled
Drake
24 May, 2023, 16:18

You need to do this because you need the ID to be 6 chars in length?

Vincent Ca
24 May, 2023, 16:18

Yes !

Drake
24 May, 2023, 16:21

I'm not sure how this collection is used and where you need the speed...some things to consider:

  1. getDocument() is faster than listDocuments() because getDocument() uses the cache
  2. I would make sure to have a unqiue index to ensure uniqueness at the database level
Vincent Ca
24 May, 2023, 16:26

It's for all collections that have an ID attribute. I need all users, tickets and reservations to have a 6 characters long ID, so it's easily readable and shareable. But getDocument() need the document Id in parameters, so I can't ? And yes I have added an index on the ID attribute but I don't really understand how indexes work...

Drake
24 May, 2023, 16:29

It's for all collections that have an ID attribute. I need all users, tickets and reservations to have a 6 characters long ID, so it's easily readable and shareable. But getDocument() need the document Id in parameters, so I can't ?

Keep in mind, you can use a custom 6 character ID for the document id. Then you can use getDocument() on that 6 character ID.

I have added an index on the ID attribute but I don't really understand how indexes work...

They just work behind the scenes. You don't really do anything. They speed up queries and provide restrictions (if it's a unique index)

Vincent Ca
24 May, 2023, 16:31

how can I use a custom 6 characters ID as the document ID ? With createDocument()#documentId parameter ?

Drake
24 May, 2023, 16:31

yes, you pass ID.custom(yourId) instead of ID.unique()

Vincent Ca
24 May, 2023, 16:33

Oh okay I thought It needed to be formatted like default ID.unique(). Thank you very much. So I can add an index on the documentId ?

Drake
24 May, 2023, 16:33

there's no need to add an index on the document ID

Vincent Ca
24 May, 2023, 16:41
Vincent Ca
24 May, 2023, 16:42

How do I know if the document was found please ?

Vincent Ca
24 May, 2023, 16:42

In nodeJS

Vincent Ca
24 May, 2023, 16:42

with then() catch() ?

Vincent Ca
24 May, 2023, 16:44

ty

Vincent Ca
24 May, 2023, 16:54

Steven, can I change a document ID in a function ?

Vincent Ca
24 May, 2023, 16:57

I can't handle making 2 requests in my apps just to check if the ID already exists before creating a document

Vincent Ca
24 May, 2023, 16:58

I think I need to do this with a function

Drake
24 May, 2023, 17:10

No, you can't change a document id

Drake
24 May, 2023, 17:10

I mean...you can just try to create it...if it throws an error saying it's a duplicate, try again

Vincent Ca
24 May, 2023, 17:11

ty

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more