Customize Entities
You can extend the fields of articles and categories through the TypeORM ChildEntity mechanism. Below, we provide some examples to illustrate how to add a boolean field when you want to record whether an article should be published.
First, you need to create an Entity that extends from BaseArticleEntity and add an onShelf field to it.
import { ChildEntity } from 'typeorm';
import { BaseArticleEntity } from '@rytass/cms-base-nestjs-module';
@ChildEntity()
export class ArticleEntity extends BaseArticleEntity {
@Column('boolean', { default: true })
onShelf: boolean;
}
Next, you need to register this entity in the forRoot method.
import { Module } from '@nestjs/common';
import { CMSBaseModule } from '@rytass/cms-base-nestjs-module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ArticleEntity } from './article.entity';
@Module({
imports: [
// ... (typeorm register)
TypeOrmModule.forFeature([ArticleEntity]), // Remember, forFeature register is required
CMSBaseModule.forRoot({
articleEntity: ArticleEntity,
}),
],
})
export class AppModule {}
After all, when you use ArticleBaseService, you can access these custom-defined columns. Remember, You need to inform the service of how you’ve defined it through generics.
import { Injectable } from '@nestjs/common';
import { ArticleEntity } from './article.entity';
import { ArticleBaseService, ArticleBaseDto } from '@rytass/cms-base-nestjs-module';
@Injectable()
export class AppService {
constructor(
private readonly articleService: ArticleBaseService<ArticleEntity>,
) {}
findById(id: string): Promise<ArticleBaseDto<ArticleEntity>> {
return this.articleService.findById(id);
}
}
In addition to defining the generic when the Service is referenced, you can also override the definition when using a method. In this case, the definition provided in the method will take precedence. Also, when you create an article and a new version using a custom Entity, the Library will automatically include your custom fields.
import { Injectable } from '@nestjs/common';
import { ArticleEntity } from './article.entity';
import { ArticleBaseService, ArticleBaseDto } from '@rytass/cms-base-nestjs-module';
@Injectable()
export class AppService {
constructor(
private readonly articleService: ArticleBaseService,
) {}
findById(id: string): Promise<ArticleBaseDto<ArticleEntity>> {
return this.articleService.findById<ArticleEntity>(id);
}
createEmptyArticle(title: string): Promise<ArticleEntity> {
return this.articleService.create({
onShelf: false,
title,
content: EMPTY_QUADRATS_ELEMENTS,
});
}
}