Skip to content

Commit

Permalink
feat(markdown): import post markdown service
Browse files Browse the repository at this point in the history
  • Loading branch information
wibus-wee committed Jul 19, 2022
1 parent b36f9cd commit 6bd4079
Show file tree
Hide file tree
Showing 4 changed files with 133 additions and 15 deletions.
3 changes: 1 addition & 2 deletions src/modules/markdown/markdown.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Auth } from '~/common/decorator/auth.decorator';
import { HTTPDecorators } from '~/common/decorator/http.decorator';
import { ApiName } from '~/common/decorator/openapi.decorator';
import { CategoryModel } from '../category/category.model';
import { ExportMarkdownDto, ExportSomeMarkdownsDto } from './markdown.dto';
import { ExportMarkdownDto } from './markdown.dto';
import { MarkdownService } from './markdown.service';
import JSZip from 'jszip';
import { join } from 'path';
Expand All @@ -22,7 +22,6 @@ export class MarkdownController {
@ApiProperty({ description: '导出部分 Markdown 文件' })
@HTTPDecorators.Bypass
async exportSomeMarkdowns(@Query() { showTitle, slug, yaml }: ExportMarkdownDto, @Body() { id }: any, @Res() res) {
console.log(id)
const { posts, pages } = await this.markdownService.getSomeMarkdownData(id); // 获取部分数据
// 如果 posts 和 pages 合起来只有一条数据,则直接导出
if (id.length === 1) {
Expand Down
9 changes: 1 addition & 8 deletions src/modules/markdown/markdown.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @author: Wibus
* @Date: 2022-07-18 21:25:29
* @LastEditors: Wibus
* @LastEditTime: 2022-07-19 11:21:33
* @LastEditTime: 2022-07-19 11:36:22
* Coding With IU
*/

Expand Down Expand Up @@ -66,10 +66,3 @@ export class ExportMarkdownDto {
@ApiProperty({ description: 'Markdown 文件第一行是否显示标题' })
showTitle?: boolean;
}

export class ExportSomeMarkdownsDto {
@IsString()
// @Transform(({ value }) => value.split(',')) // 将字符串转换成数组
@ApiProperty({ description: '要导出的 Markdown 文件 ID' })
id: string[];
}
16 changes: 14 additions & 2 deletions src/modules/markdown/markdown.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @author: Wibus
* @Date: 2022-07-18 21:25:36
* @LastEditors: Wibus
* @LastEditTime: 2022-07-18 21:33:04
* @LastEditTime: 2022-07-19 11:37:07
* Coding With IU
*/

Expand All @@ -17,4 +17,16 @@ export type MarkdownMetaType = {
export interface MarkdownYAMLProps {
meta: MarkdownMetaType;
text: string;
}
}

export const ArticleType = Object.freeze({
Post: 'post',
Note: 'note',
Page: 'page',
} as const)

export enum ArticleTypeEnum {
Post = 'post',
Note = 'note',
Page = 'page',
}
120 changes: 117 additions & 3 deletions src/modules/markdown/markdown.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DbService } from '@app/db';
import { InjectModel } from '@app/db/model.transformer';
import { Injectable } from '@nestjs/common';
import { Injectable, InternalServerErrorException, Logger } from '@nestjs/common';
import { ReturnModelType } from '@typegoose/typegoose';
import { omit } from 'lodash';
import { CategoryModel } from '../category/category.model';
Expand All @@ -9,6 +9,8 @@ import { PostModel } from '../post/post.model';
import { MarkdownYAMLProps } from './markdown.interface';
import { dump } from 'js-yaml';
import JSZip from 'jszip';
import { DataDto } from './markdown.dto';
import { Types } from 'mongoose';

@Injectable()
export class MarkdownService {
Expand All @@ -22,7 +24,14 @@ export class MarkdownService {
private readonly dbService: DbService,
) { }

// 将 Markdown 数据转换成 YAML 数据 的「转换器」
/**
* convert Markdown 到 YAML 转换器
* @param item 文章或页面
* @param metaData 文章或页面的 meta 数据
* @param yaml 是否生成 YAML 格式
* @param showTitle 是否显示标题
* @returns 文章或页面的 Markdown 格式
*/
convertor = <
T extends {
title: string,
Expand Down Expand Up @@ -55,13 +64,20 @@ export class MarkdownService {
}
}

/**
* 获取文章或页面的 Markdown 格式
*/
async getAllMarkdownData() {
return {
posts: await this.postModel.find({}).populate('category'), // 待讨论:加密文章是否允许导出?
pages: await this.pageModel.find({}).lean(),
}
}

/**
* 获取文章或页面的 Markdown 格式
* @param id 文章或页面的 id
*/
async getSomeMarkdownData(id: string[]) {
const docs = await Promise.all([
this.postModel.find({ _id: { $in: id } }).populate('category'),
Expand All @@ -74,6 +90,13 @@ export class MarkdownService {
};
}

/**
* 生成 Markdown 格式
* @param yamlProp 文章或页面的 Markdown 数据
* @param yaml 是否生成 YAML 格式
* @param showTitle 是否显示标题
* @returns 文章或页面的 Markdown 格式
*/
markdownBuilder(
yamlProp: MarkdownYAMLProps,
yaml?: boolean,
Expand Down Expand Up @@ -109,6 +132,9 @@ ${text.trim()}

}

/**
* 导出 Zip
*/
async generateArchive({
documents,
options = {},
Expand All @@ -129,4 +155,92 @@ ${text.trim()}
return zip
}

}
/**
* genDate 格式化日期
* @param item Data
*/
private readonly genDate = (item: DataDto) => {
const { meta } = item
if (!meta) {
return {
created: new Date(),
modified: new Date(),
}
}
const { date, updated } = meta
return {
created: date ? new Date(date) : new Date(),
modified: updated
? new Date(updated)
: date
? new Date(date)
: new Date(),
}
}

/**
* 导入文章
* @param data 数据
*/
async importPostMarkdownData(data: DataDto[]) {

const categoryNameAndId = ( // 获取分类名称和 id
await (await this.categoryModel.find().lean()).map(item => {
return {
name: item.name,
_id: item._id,
slug: item.slug,
}
})
)
const importWithCategoryOrCreate = async (name?: string) => {
if (!name) return // 如果没有分类名称,则不创建分类
const hasCategory = categoryNameAndId.find(item => item.name === name || item.slug === name) // 判断是否有分类
if (hasCategory) {
return hasCategory
} else { // 如果没有分类,则创建分类
const category = await this.categoryModel.create({
name,
slug: name,
type: 0 // 类型为 0 -- Category
})
categoryNameAndId.push({
name: category.name,
_id: category._id,
slug: category.slug,
}) // 添加到分类名称和 id 列表
await category.save() // 保存分类
return category
}
}
let count = 1
const models = [] as PostModel[]
const defaultCategory = await this.categoryModel.findOne()
if (!defaultCategory) throw new InternalServerErrorException('未找到分类')
for await (const item of data) {
if (item.meta) {
const category = await importWithCategoryOrCreate(item.meta.categories?.shift())
models.push({
title: item.meta.title,
slug: item.meta.slug || item.meta.title.replace(/\s/g, '-'),
text: item.text,
...this.genDate(item),
categoryId: category?._id || defaultCategory._id,
} as PostModel)
} else {
models.push({
title: `未命名-${count++}`,
slug: new Date().getTime(),
text: item.text,
...this.genDate(item),
categoryId: new Types.ObjectId(defaultCategory._id),
} as any as PostModel)
}
}

return await this.postModel.insertMany(models, { ordered: false }).catch(err => {
Logger.warn(`一篇或多篇文章导入失败:${err.message}`, MarkdownService.name)
})

}
}

0 comments on commit 6bd4079

Please sign in to comment.