feat: add highlight for article html.

This commit is contained in:
Ivan Li
2021-07-03 12:40:52 +08:00
parent 76862b738d
commit 51d5ac6ee6
3 changed files with 40 additions and 1 deletions

View File

@ -12,6 +12,7 @@ import { Article } from './entities/article.entity';
import { CreateArticleInput } from './dto/create-article.input';
import { UpdateArticleInput } from './dto/update-article.input';
import * as marked from 'marked';
import { getLanguage, highlight } from 'highlight.js';
@Resolver(() => Article)
export class ArticlesResolver {
@ -49,7 +50,22 @@ export class ArticlesResolver {
@ResolveField(() => String)
async html(@Parent() article: Article) {
return marked(article.content);
const tokens = marked.lexer(article.content);
const index = tokens.findIndex((token) => ['heading'].includes(token.type));
if (index !== -1) {
tokens.splice(index, 1);
}
return marked.parser(tokens, {
gfm: true,
smartLists: true,
smartypants: true,
langPrefix: 'hljs language-',
highlight: (code, language) => {
return highlight(code, {
language: getLanguage(language) ? language : 'plaintext',
}).value;
},
});
}
@ResolveField(() => String, { nullable: true })