How to create UUIDs for new entities?

In a Button Script, I am going to duplicate an entity, and also duplicate the entities in one of its collections (a partial “deep clone”).

As suggested in the API examples, it would be useful to pre-set the fibery/id's of some of these clones I’m going to create, to simplify adding them to the new parent’s collection.

How can I generate a UUID in a script?

Not sure why you want to set the ID, as opposed to just creating an entity and reading its ID, but you can always just use a random number for a part of the UUID if you want to create your own each time:
Math.floor(Math.random * 10000)
should get you an integer between 0 and 9999.
You will probably need to make use of .toString() as well

const parent = await fibery.createEntity('AppName/ParentTypeName', { 'name': 'P' })
const child = await fibery.createEntity('AppName/ChildTypeName', { 'name': 'C' })
await fibery.addCollectionItem('AppName/ParentTypeName',parent['Id'],'ChildFieldName',child['Id'])

Any use?

So, is there not a strict requirement that the fibery/id field contains a “real” UUID (mac address and timestamp)?
– –

I have noticed it can be a lot more efficient to lump all the entity creations/updates into as few API calls as possible, and execute them under under a single Promise.all(), as opposed to a series of awaits.

If I can set and use the fibery/ids of the new entities I am creating (cloning) before creating them, then I will not need to read them back after creation = big time savings.

“Setting fibery/id is optional and might be useful for working with Entity right after creation.”

As far as I know, any unique identifier of the correct format works, but I’ll double-check.

Makes sense. I hadn’t imagined that this process was slowing you down, but it’s a good point.

As far as I know there is no utility method to generated uuid for now. It would be nice to have such method, will propose that to maintainer. Meanwhile, you may try the following snippet

function uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

It is not so universally unique but would be enough for your use case.
All credits to stackoverflow

2 Likes

Thanks @Viktar_Zhuk – I believe it requires UUID v1.

You must not. We are using uuid v4 all over the place.

I’ve double checked server side source code it accepts any UUID whether it v1 or v4. I can guarantee that v4 will be supported in long term cause we use this version in majority cases. In any case, there is no way to generate UUID value beforehand using our platform. So you may stick to own implementation or abandon the idea.

1 Like

You can use this code now:

const utils = context.getService('utils');
console.log(utils.uuid());
3 Likes