Skip to content

Commit

Permalink
feat: use crypto.getRandomValues instead of Math.random
Browse files Browse the repository at this point in the history
  • Loading branch information
jiho-kr committed Dec 15, 2023
1 parent 4a21124 commit 036af1c
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
4 changes: 3 additions & 1 deletion spec/custom-entity/custom-entity.entity.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import crypto from 'crypto';

import { IsString, IsNotEmpty, IsOptional } from 'class-validator';
import { BaseEntity, BeforeInsert, Column, DeleteDateColumn, Entity, PrimaryColumn } from 'typeorm';

Expand Down Expand Up @@ -26,6 +28,6 @@ export class CustomEntity extends BaseEntity {

@BeforeInsert()
setPrimaryKey() {
this.uuid = this.uuid ?? `${Date.now()}${Math.floor(Math.random() * 10_000)}`;
this.uuid = this.uuid ?? `${Date.now()}${crypto.getRandomValues(new Uint16Array(1))[0]}`;
}
}
7 changes: 5 additions & 2 deletions spec/multiple-primary-key/multiple-primary-key.entity.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import crypto from 'crypto';

import { IsOptional, IsString } from 'class-validator';
import { BaseEntity, BeforeInsert, Column, DeleteDateColumn, Entity, PrimaryColumn } from 'typeorm';

import { GROUP } from '../../src/lib/interface';

@Entity('base')
export class MultiplePrimaryKeyEntity extends BaseEntity {
@PrimaryColumn()
Expand All @@ -22,7 +25,7 @@ export class MultiplePrimaryKeyEntity extends BaseEntity {

@BeforeInsert()
setPrimaryKey() {
this.uuid1 = this.uuid1 ?? `${Math.floor(Math.random() * 10_000)}${Date.now()}`;
this.uuid2 = this.uuid2 ?? `${Math.floor(Math.random() * 10_000)}${Date.now()}`;
this.uuid1 = this.uuid1 ?? `${crypto.getRandomValues(new Uint16Array(1))[0]}${Date.now()}`;
this.uuid2 = this.uuid2 ?? `${crypto.getRandomValues(new Uint16Array(1))[0]}${Date.now()}`;
}
}

0 comments on commit 036af1c

Please sign in to comment.