Skip to content

Instantly share code, notes, and snippets.

@angelxmoreno
Last active April 26, 2022 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angelxmoreno/f54733b24a11ee79d7d3f5f3b6486b46 to your computer and use it in GitHub Desktop.
Save angelxmoreno/f54733b24a11ee79d7d3f5f3b6486b46 to your computer and use it in GitHub Desktop.
import {
BeforeCreate,
BeforeUpdate,
Collection,
Entity,
EntityManager,
EntityRepositoryType,
ManyToOne,
OneToMany,
Property,
} from '@mikro-orm/core';
import { EntityBase } from '@database/EntityBase';
import { CategoryRepository } from '@database/repositories/CategoryRepository';
import { IsDefined, IsOptional, IsString, IsUUID, Length, Validate } from 'class-validator';
import ExistsInTable from '@validators/ExistsInTable';
import { AdEntity } from '@database/entities/AdEntity';
@Entity({ customRepository: () => CategoryRepository })
export class CategoryEntity extends EntityBase {
[EntityRepositoryType]?: CategoryRepository;
@Property({ length: 100, nullable: false, type: 'varchar(100)' })
@IsDefined()
@IsString()
@Length(2, 100)
name: string;
@Property({ length: 200, nullable: false, type: 'varchar(200)' })
slug: string;
@Property({ nullable: true, default: null, type: 'text' })
@IsOptional()
@IsString()
@Length(1, 1000)
description?: string;
@Property({ persist: false, nullable: true })
@IsOptional()
@IsUUID()
@Validate(ExistsInTable, ['CategoryEntity', 'id'])
parentId?: string | null;
@ManyToOne({
entity: () => CategoryEntity,
// mappedBy: 'children',
nullable: true,
})
parent?: CategoryEntity;
@OneToMany({
entity: () => CategoryEntity,
mappedBy: 'parent',
nullable: true,
})
children? = new Collection<CategoryEntity>(this);
@OneToMany('AdEntity', 'category')
ads = new Collection<AdEntity>(this);
@BeforeCreate()
@BeforeUpdate()
async makeSlug({ em }: { entity: CategoryEntity; em: EntityManager }) {
if (!this.slug) {
const slugBase = this.name
.toLowerCase()
.replace(/[^a-z0-9]/g, '-')
.replace(/-+/g, '-')
.trim();
let slug = slugBase;
let count = 0;
let iterator = 1;
do {
count = await em.count(CategoryEntity, { slug });
if (count > 0) {
console.log(`${slug} already exists`);
slug = `${slugBase}-${iterator}`;
iterator++;
}
} while (count > 0);
this.slug = slug;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment