diff --git a/src/article/article.module.ts b/src/article/article.module.ts index 53dfabf..ca575e7 100644 --- a/src/article/article.module.ts +++ b/src/article/article.module.ts @@ -3,10 +3,13 @@ import { CategoryController } from './controller/category.controller'; import { CategoryService } from './service/category.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Category } from './entity/category.entity'; +import { ArticleService } from './service/article.service'; +import { Article } from './entity/article.entity'; +import { ArticleController } from './controller/article.controller'; @Module({ - controllers: [CategoryController], - imports: [TypeOrmModule.forFeature([Category])], - providers: [CategoryService], + controllers: [CategoryController, ArticleController], + imports: [TypeOrmModule.forFeature([Category, Article])], + providers: [CategoryService, ArticleService], }) export class ArticleModule {} diff --git a/src/article/controller/article.controller.ts b/src/article/controller/article.controller.ts index 2102be2..ca1d309 100644 --- a/src/article/controller/article.controller.ts +++ b/src/article/controller/article.controller.ts @@ -1,4 +1,111 @@ -import { Controller } from '@nestjs/common'; +import { + Body, + Controller, + Delete, + Get, + Param, + Post, + Put, + Query, +} from '@nestjs/common'; +import { CreateArticleRequest } from '../dto/create-article.request'; +import { ArticleService } from '../service/article.service'; +import { ApiBearerAuth, ApiOkResponse, getSchemaPath } from '@nestjs/swagger'; +import { ArticleVo } from '../vo/article.vo'; +import { ArticleMapper } from '../mapper/article.mapper'; +import { SearchArticleFilter } from '../dto/search-article.filter'; +import { PageResult } from '../../core/vo/page-result'; +import { PageResultMapper } from '../../core/mapper/page-result.mapper'; +import { Article } from '../entity/article.entity'; @Controller('articles') -export class ArticleController {} +export class ArticleController { + constructor(private readonly articleService: ArticleService) {} + @Post() + @ApiBearerAuth() + @ApiOkResponse({ + type: ArticleVo, + }) + async create( + @Body() createArticle: CreateArticleRequest, + ): Promise { + return ArticleMapper.toVo(await this.articleService.create(createArticle)); + } + + @Get() + @ApiBearerAuth() + @ApiOkResponse({ + description: '咨询分页列表', + schema: { + allOf: [ + { $ref: getSchemaPath(PageResult) }, // 引用 PageResult 模型 + { + properties: { + data: { + type: 'array', + items: { $ref: getSchemaPath(ArticleVo) }, // 泛型内容具体化 + }, + }, + }, + ], + }, + }) + async search( + @Query() searchArticleFilter: SearchArticleFilter, + ): Promise> { + const [data, total] = await this.articleService.search(searchArticleFilter); + return PageResultMapper.toPageResult( + ArticleMapper.toVos(data), + searchArticleFilter.getPage(), + searchArticleFilter.getSize(), + total, + ); + } + + @Get(':id') + @ApiBearerAuth() + @ApiOkResponse({ + type: ArticleVo, + }) + async get(@Param('id') id: string) { + return ArticleMapper.toVo(await this.articleService.get(id)); + } + + @Put(':id') + @ApiBearerAuth() + @ApiOkResponse({ + type: ArticleVo, + }) + async update( + @Param('id') id: string, + @Body() updateArticle: CreateArticleRequest, + ) { + return ArticleMapper.toVo( + await this.articleService.update(id, updateArticle), + ); + } + + @Put(':id/publish') + @ApiBearerAuth() + @ApiOkResponse({ + type: ArticleVo, + }) + async publish(@Param('id') id: string) { + return ArticleMapper.toVo(await this.articleService.publish(id)); + } + + @Put(':id/close') + @ApiBearerAuth() + @ApiOkResponse({ + type: ArticleVo, + }) + async close(@Param('id') id: string) { + return ArticleMapper.toVo(await this.articleService.close(id)); + } + + @Delete(':id') + @ApiBearerAuth() + async delete(@Param('id') id: string) { + await this.articleService.delete(id); + } +} diff --git a/src/article/dto/create-article.request.ts b/src/article/dto/create-article.request.ts new file mode 100644 index 0000000..fd6ffe1 --- /dev/null +++ b/src/article/dto/create-article.request.ts @@ -0,0 +1,21 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsNotEmpty, Length, MaxLength } from 'class-validator'; + +export class CreateArticleRequest { + @ApiProperty({ + example: '测试文章标题', + }) + @IsNotEmpty({ message: '文章标题不能为空' }) + @Length(4, 120, { message: '文章标题长度必须在4到120字符之间' }) + title: string; + + @ApiProperty() + @IsNotEmpty({ message: '文章分类不能为空' }) + categoryId: string; + + @ApiProperty({ + example: '测试文章内容', + }) + @MaxLength(10000, { message: '文章内容长度不能超过10000字符' }) + content: string; +} diff --git a/src/article/dto/search-article.filter.ts b/src/article/dto/search-article.filter.ts new file mode 100644 index 0000000..d3576ee --- /dev/null +++ b/src/article/dto/search-article.filter.ts @@ -0,0 +1,3 @@ +import { BaseFilter } from '../../core/dto/base.filter'; + +export class SearchArticleFilter extends BaseFilter {} diff --git a/src/article/dto/update-article.request.ts b/src/article/dto/update-article.request.ts new file mode 100644 index 0000000..dc73b0b --- /dev/null +++ b/src/article/dto/update-article.request.ts @@ -0,0 +1,3 @@ +import { CreateArticleRequest } from './create-article.request'; + +export class UpdateArticleRequest extends CreateArticleRequest {} diff --git a/src/article/entity/article.entity.ts b/src/article/entity/article.entity.ts new file mode 100644 index 0000000..1cbe784 --- /dev/null +++ b/src/article/entity/article.entity.ts @@ -0,0 +1,29 @@ +import { TraceableEntity } from '../../core/entity/traceable.entity'; +import { Column, Entity, ManyToOne, JoinColumn } from 'typeorm'; +import { ArticleStatusEnum } from '../enum/article-status.enum'; +import { Category } from './category.entity'; + +@Entity() +export class Article extends TraceableEntity { + @Column() + title: string; + + @Column({ + type: 'text', + nullable: true, + }) + content: string; + + @ManyToOne(() => Category) + @JoinColumn({ + name: 'category_id', + }) + category: Category; + + @Column({ + type: 'enum', + enum: ArticleStatusEnum, + default: ArticleStatusEnum.DRAFT, + }) + status: ArticleStatusEnum = ArticleStatusEnum.DRAFT; +} diff --git a/src/article/enum/article-status.enum.ts b/src/article/enum/article-status.enum.ts new file mode 100644 index 0000000..fda6d17 --- /dev/null +++ b/src/article/enum/article-status.enum.ts @@ -0,0 +1,5 @@ +export enum ArticleStatusEnum { + DRAFT = 'draft', + PUBLISHED = 'published', + CLOSED = 'closed', +} diff --git a/src/article/error/article.error.ts b/src/article/error/article.error.ts new file mode 100644 index 0000000..11924db --- /dev/null +++ b/src/article/error/article.error.ts @@ -0,0 +1,8 @@ +import { ErrorResponse } from '../../core/error/error.response'; + +export const ArticleError: Record = { + NOT_FOUND: { + code: 4001, + message: 'Article not found', + }, +}; diff --git a/src/article/error/category.error.ts b/src/article/error/category.error.ts index 6e75b8e..6a41017 100644 --- a/src/article/error/category.error.ts +++ b/src/article/error/category.error.ts @@ -1,4 +1,4 @@ -import { ErrorResponse } from '../../core/errors/error.response'; +import { ErrorResponse } from '../../core/error/error.response'; export const CategoryError: Record = { NOT_FOUND: { diff --git a/src/article/mapper/article.mapper.ts b/src/article/mapper/article.mapper.ts new file mode 100644 index 0000000..5efc580 --- /dev/null +++ b/src/article/mapper/article.mapper.ts @@ -0,0 +1,24 @@ +import { Article } from '../entity/article.entity'; +import { ArticleVo } from '../vo/article.vo'; +import { CategoryMapper } from './category.mapper'; +import { DateUtil } from '../../core/util/date.util'; +import { UserMapper } from '../../core/mapper/user.mapper'; + +export class ArticleMapper { + static toVo(entity: Article): ArticleVo { + return { + id: entity.id, + title: entity.title, + content: entity.content, + category: CategoryMapper.toVo(entity.category), + status: entity.status, + createdTime: DateUtil.format(entity.createdTime), + updatedTime: DateUtil.format(entity.updatedTime), + createBy: UserMapper.toVo(entity.createBy), + updateBy: UserMapper.toVo(entity.updateBy), + }; + } + static toVos(entities: Article[]): ArticleVo[] { + return entities.map((entity) => this.toVo(entity)); + } +} diff --git a/src/article/service/article.service.ts b/src/article/service/article.service.ts new file mode 100644 index 0000000..1b89adc --- /dev/null +++ b/src/article/service/article.service.ts @@ -0,0 +1,79 @@ +import { Injectable } from '@nestjs/common'; +import { CreateArticleRequest } from '../dto/create-article.request'; +import { Repository } from 'typeorm'; +import { Article } from '../entity/article.entity'; +import { InjectRepository } from '@nestjs/typeorm'; +import { CategoryService } from './category.service'; +import { SearchArticleFilter } from '../dto/search-article.filter'; +import { BizException } from '../../core/exception/biz.exception'; +import { ArticleError } from '../error/article.error'; +import { ArticleStatusEnum } from '../enum/article-status.enum'; + +@Injectable() +export class ArticleService { + constructor( + @InjectRepository(Article) + private readonly articleRepository: Repository
, + private readonly categoryService: CategoryService, + ) {} + + async create(createArticleRequest: CreateArticleRequest) { + const category = await this.categoryService.get( + createArticleRequest.categoryId, + ); + const article = new Article(); + article.title = createArticleRequest.title; + article.content = createArticleRequest.content; + article.category = category; + return this.articleRepository.save(article); + } + + async search(searchArticleFilter: SearchArticleFilter) { + return this.articleRepository.findAndCount({ + where: searchArticleFilter.getConditions(), + skip: searchArticleFilter.getSkip(), + take: searchArticleFilter.getSize(), + order: searchArticleFilter.getOrderBy(), + }); + } + + async get(id: string) { + const article = await this.articleRepository.findOneBy({ id }); + if (!article) { + throw new BizException(ArticleError.NOT_FOUND); + } + return article; + } + + async update(id: string, updateArticle: CreateArticleRequest) { + const article = await this.articleRepository.findOneBy({ id }); + if (!article) { + throw new BizException(ArticleError.NOT_FOUND); + } + if (article.category.id !== updateArticle.categoryId) { + article.category = await this.categoryService.get( + updateArticle.categoryId, + ); + } + article.title = updateArticle.title; + article.content = updateArticle.content; + return this.articleRepository.save(article); + } + + async publish(id: string) { + const article = await this.get(id); + article.status = ArticleStatusEnum.PUBLISHED; + return this.articleRepository.save(article); + } + + async close(id: string) { + const article = await this.get(id); + article.status = ArticleStatusEnum.CLOSED; + return this.articleRepository.save(article); + } + + async delete(id: string) { + const article = await this.get(id); + await this.articleRepository.remove(article); + } +} diff --git a/src/article/service/category.service.ts b/src/article/service/category.service.ts index 4ae63c6..f036812 100644 --- a/src/article/service/category.service.ts +++ b/src/article/service/category.service.ts @@ -4,7 +4,7 @@ import { Category } from '../entity/category.entity'; import { Repository } from 'typeorm'; import { CreateCategoryRequest } from '../dto/create-category.request'; import { SearchCategoryFilter } from '../dto/search-category.filter'; -import { BizException } from '../../core/exceptions/biz.exception'; +import { BizException } from '../../core/exception/biz.exception'; import { CategoryError } from '../error/category.error'; import { UpdateCategoryRequest } from '../dto/update-category.request'; import { UserService } from '../../core/service/user.service'; diff --git a/src/article/vo/article.vo.ts b/src/article/vo/article.vo.ts new file mode 100644 index 0000000..6875031 --- /dev/null +++ b/src/article/vo/article.vo.ts @@ -0,0 +1,21 @@ +import { TraceableVo } from '../../core/vo/traceable.vo'; +import { ArticleStatusEnum } from '../enum/article-status.enum'; +import { ApiProperty, ApiSchema } from '@nestjs/swagger'; +import { CategoryVo } from './category.vo'; + +@ApiSchema({ + name: 'Article', +}) +export class ArticleVo extends TraceableVo { + @ApiProperty() + title: string; + + @ApiProperty() + content: string; + + @ApiProperty() + category: CategoryVo; + + @ApiProperty() + status: ArticleStatusEnum; +} diff --git a/src/core/errors/error.response.ts b/src/core/error/error.response.ts similarity index 100% rename from src/core/errors/error.response.ts rename to src/core/error/error.response.ts diff --git a/src/core/errors/user.error.ts b/src/core/error/user.error.ts similarity index 100% rename from src/core/errors/user.error.ts rename to src/core/error/user.error.ts diff --git a/src/core/exceptions/biz.exception.ts b/src/core/exception/biz.exception.ts similarity index 77% rename from src/core/exceptions/biz.exception.ts rename to src/core/exception/biz.exception.ts index 9720d70..30775a8 100644 --- a/src/core/exceptions/biz.exception.ts +++ b/src/core/exception/biz.exception.ts @@ -1,5 +1,5 @@ import { HttpException, HttpStatus } from '@nestjs/common'; -import { ErrorResponse } from '../errors/error.response'; +import { ErrorResponse } from '../error/error.response'; export class BizException extends HttpException { constructor(error: ErrorResponse) { diff --git a/src/core/exceptions/global-exception.filter.ts b/src/core/exception/global-exception.filter.ts similarity index 96% rename from src/core/exceptions/global-exception.filter.ts rename to src/core/exception/global-exception.filter.ts index 4a15c71..21b697c 100644 --- a/src/core/exceptions/global-exception.filter.ts +++ b/src/core/exception/global-exception.filter.ts @@ -5,7 +5,7 @@ import { HttpException, HttpStatus, } from '@nestjs/common'; -import { ErrorResponse } from '../errors/error.response'; +import { ErrorResponse } from '../error/error.response'; @Catch() export class GlobalExceptionFilter implements ExceptionFilter { diff --git a/src/core/pipe/global-validation.pipe.ts b/src/core/pipe/global-validation.pipe.ts index 65cd8ec..9aaba36 100644 --- a/src/core/pipe/global-validation.pipe.ts +++ b/src/core/pipe/global-validation.pipe.ts @@ -1,5 +1,5 @@ import { HttpStatus, ValidationError, ValidationPipe } from '@nestjs/common'; -import { ErrorResponse } from '../errors/error.response'; +import { ErrorResponse } from '../error/error.response'; export class GlobalValidationPipe extends ValidationPipe { constructor() { diff --git a/src/main.ts b/src/main.ts index 3a5fb65..7962950 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,7 +2,7 @@ import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { SnowflakeUtil } from './core/util/snowflake.util'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; -import { GlobalExceptionFilter } from './core/exceptions/global-exception.filter'; +import { GlobalExceptionFilter } from './core/exception/global-exception.filter'; import { GlobalValidationPipe } from './core/pipe/global-validation.pipe'; async function bootstrap() {