Skip to content

Commit

Permalink
feat: Add support for reading articles from files. (#384)
Browse files Browse the repository at this point in the history
  • Loading branch information
nzdjb committed Apr 21, 2024
1 parent 4494d15 commit 16a4d58
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/article.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { marked } from 'marked';
import { readFileSync } from 'node:fs';
import sanitizeHTML from 'sanitize-html';

const sanitizerSettings: sanitizeHTML.IOptions = {
Expand All @@ -11,14 +12,23 @@ export interface Link {
title: string;
}

export interface ArticleConfig {
interface ArticleBaseConfig {
title: string;
author?: string;
date: Date;
content: string;
published?: boolean;
}

interface ArticleStringConfig extends ArticleBaseConfig {
content: string;
}

interface ArticleFileConfig extends ArticleBaseConfig {
contentFile: string;
}

export type ArticleConfig = ArticleStringConfig | ArticleFileConfig;

export class Article {
readonly title: string;
readonly content: string;
Expand All @@ -30,8 +40,9 @@ export class Article {
this.title = input.title;
this.author = input.author;
this.date = input.date.toISOString().split('T')[0];
const content = "content" in input ? input.content : readFileSync(input.contentFile).toString();
this.content = sanitizeHTML(
marked.parse(input.content, { async: false }) as string,
marked.parse(content, { async: false }) as string,
sanitizerSettings
);
this.published = input.published ?? true;
Expand Down
21 changes: 21 additions & 0 deletions test/article.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,27 @@ await describe('article', async () => {
equal(article.published, true);
});

await test('creates with contentFile', () => {
const title = 'test article';
const author = 'Bob';
const date = new Date('January 1, 2023 12:34:56');
const contentFile = 'test/inputs/test.md';
const published = true;
const article = new Article({
title,
author,
date,
contentFile,
published,
});
ok(article instanceof Article);
equal(article.title, title);
equal(article.author, author);
equal(article.date, '2023-01-01');
equal(article.content, '<h1>test</h1>\n');
equal(article.published, true);
});

await test('creates with defaults', () => {
const title = 'test article';
const date = new Date('January 1, 2023');
Expand Down
1 change: 1 addition & 0 deletions test/inputs/test.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>test</h1>

0 comments on commit 16a4d58

Please sign in to comment.