How to using uuid v7 in adonis? #4985
-
I want to using uuid v7, how to implement that? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey @edikurniawan-dev! 👋🏻 You can approach this the same way you would in any other codebase. AdonisJS doesn't introduce anything special in this regard, it just offers more built-in features when needed. If you want to use UUIDs, simply install the Here’s an example using a mixin: import { v7 as randomUUID } from 'uuid';
import { beforeCreate, column } from '@adonisjs/lucid/orm';
import type { BaseModel } from '@adonisjs/lucid/orm';
import type { NormalizeConstructor } from '@adonisjs/core/types/helpers';
/**
* A mixin for adding a UUID v7 primary key to a model and automatically generating it
*/
export const WithPrimaryUuid = <Model extends NormalizeConstructor<typeof BaseModel>>(superclass: Model) => {
class WithPrimaryUuidClass extends superclass {
static selfAssignPrimaryKey = true;
@column({ isPrimary: true })
declare id: string;
@beforeCreate()
static generateId(model: any) {
model.id = randomUUID();
}
}
return WithPrimaryUuidClass;
}; And usage in a model: import { compose } from '@adonisjs/core/helpers';
import { BaseModel, column } from '@adonisjs/lucid/orm';
import { WithTimestamps } from '#core/mixins/with_timestamps';
import { WithPrimaryUuid } from '#core/mixins/with_primary_uuid';
export default class Team extends compose(BaseModel, WithTimestamps, WithPrimaryUuid) {
@column()
declare name: string;
} |
Beta Was this translation helpful? Give feedback.
Hey @edikurniawan-dev! 👋🏻
You can approach this the same way you would in any other codebase. AdonisJS doesn't introduce anything special in this regard, it just offers more built-in features when needed.
If you want to use UUIDs, simply install the
uuid
package from npm and use it where appropriate. For example, if you want to use a UUID as the primary key in a model, you can either define a mixin (to keep your code DRY) or use a@beforeCreate
hook directly inside your model.Here’s an example using a mixin: