71 lines
2.4 KiB
TypeScript
71 lines
2.4 KiB
TypeScript
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
|
|
import { InjectModel } from '@nestjs/sequelize';
|
|
import { Op } from 'sequelize';
|
|
import { Article } from './models/article.model';
|
|
import { CreateArticleDto, QueryArticlesDto, ArticleVo } from './dto/article.dto';
|
|
import { ResponseCode } from '../base.dto';
|
|
|
|
@Injectable()
|
|
export class ArticlesService {
|
|
private readonly logger = new Logger(ArticlesService.name);
|
|
constructor(
|
|
@InjectModel(Article)
|
|
private readonly articleModel: typeof Article,
|
|
) { }
|
|
|
|
async create(dto: CreateArticleDto) {
|
|
const article = await this.articleModel.create({
|
|
title: dto.title,
|
|
publishedDate: dto.publishedDate as any,
|
|
htmlContent: dto.htmlContent,
|
|
coverImage: dto.coverImage,
|
|
});
|
|
return { code: ResponseCode.SUCCESS, message: 'success', data: article.toJSON() as ArticleVo };
|
|
}
|
|
|
|
async query(params: QueryArticlesDto) {
|
|
const page = Math.max(1, Number(params.page || 1));
|
|
const pageSize = Math.min(100, Math.max(1, Number(params.pageSize || 10)));
|
|
const where: any = {};
|
|
if (params.keyword) {
|
|
where.title = { [Op.like]: `%${params.keyword}%` };
|
|
}
|
|
if (params.startDate || params.endDate) {
|
|
where.publishedDate = {} as any;
|
|
if (params.startDate) (where.publishedDate as any)[Op.gte] = params.startDate as any;
|
|
if (params.endDate) (where.publishedDate as any)[Op.lte] = params.endDate as any;
|
|
}
|
|
|
|
const { rows, count } = await this.articleModel.findAndCountAll({
|
|
where,
|
|
order: [['publishedDate', 'DESC'], ['createdAt', 'DESC']],
|
|
offset: (page - 1) * pageSize,
|
|
limit: pageSize,
|
|
});
|
|
|
|
return {
|
|
code: ResponseCode.SUCCESS,
|
|
message: 'success',
|
|
data: { list: rows.map(r => r.toJSON() as ArticleVo), total: count, page, pageSize },
|
|
};
|
|
}
|
|
|
|
async getAndIncreaseReadCount(id: string) {
|
|
const article = await this.articleModel.findByPk(id);
|
|
if (!article) throw new NotFoundException('文章不存在');
|
|
article.readCount += 1;
|
|
await article.save();
|
|
return { code: ResponseCode.SUCCESS, message: 'success', data: article.toJSON() as ArticleVo };
|
|
}
|
|
|
|
async increaseReadCount(id: string) {
|
|
const article = await this.articleModel.findByPk(id);
|
|
if (!article) throw new NotFoundException('文章不存在');
|
|
article.readCount += 1;
|
|
await article.save();
|
|
return { code: ResponseCode.SUCCESS, message: 'success', data: article.toJSON() as ArticleVo };
|
|
}
|
|
}
|
|
|
|
|