14

I need a UUID field in a content type, with the help of the introduction below I have modified the file "MyType.settings.json".

https://strapi.io/documentation/3.x.x/guides/models.html#define-the-attributes

"uid": {
  "default": "",
  "type": "uuid"
},

I thought a UUID is automatically saved, but nothing happens.

How can I define and use a UUID field? Can someone give me a hint? Should I also modify the file \api\MyType\controllers\MyType.js?

Thanks in advance!

Benjamin

Benjamin Reeves
  • 553
  • 3
  • 6
  • 19

4 Answers4

10

You will have to use uuid node module. So keep your attribute and in the lifeCyle functions, set your uuid with the lib.

'use strict';

const uuid = require('uuid');

module.exports = {
  beforeCreate: async (model) => {
    model.set('uid', uuid());
  }
};
Jim LAURIE
  • 3,859
  • 1
  • 11
  • 14
2

In order to auto-generate uuid both after an entity has been saved via API and admin UI, use the lifecycle-method of your model, not the controller. The file /api/myType/models/myType.js thus may look like this:

'use strict';

const { v4: uuid } = require('uuid');

module.exports = {
  lifecycles: {
    beforeCreate: async (data) => {
      if (!data.uuid) {
        data.uuid = uuid();
      }
    },
  }
};
Albrow
  • 86
  • 5
1

You will probably also want a v4 UUID, which is the fastest to generate by a very large margin and will give you the least chance for collision with all other things being equal (can be 10x or even faster), which is what 99% of all people want to generate UUIDs for:

Work in the global UUID community, remain as unique as possible, not collide with anything else.

In addition, v4 is more secure than v1 as v1 includes the time it was made and which hardware it was created on, and has an insanely higher collision rate as today nobody respects the node field and just fills it with entropy which defeated the whole purpose of v1.

The reasons to use v4 over v1 is so stark in fact that this information should be made much more public and widespread. It is night and day. All major frameworks that only seek entropy now use v4.

import { v4 as uuid } from "uuid";
// Then just...
const myUUID = uuid()

UUID v1 was created because people, even the genius computer scientists that came up with UUID, didn't fully grasp that the address space of 128 bits alone was much better than fancy timing and node tracking. UUID v1 is a great case of over-engineering.

Nick Steele
  • 7,419
  • 4
  • 36
  • 33
1

In Strapi V4 create file ./src/api/[api-name]/content-types/[api-name]/lifecycles.js

with following content:

"use strict";

const { v4: uuid } = require("uuid");

module.exports = {
  beforeCreate: async (data) => {
    if (!data.params.data.uuid) {
      data.params.data.uuid = uuid();
    }
  },
};
Daniel
  • 839
  • 10
  • 20