diff options
author | Patryk Niedźwiedziński <pniedzwiedzinski19@gmail.com> | 2019-10-13 23:31:53 +0200 |
---|---|---|
committer | Patryk Niedźwiedziński <pniedzwiedzinski19@gmail.com> | 2019-10-13 23:31:53 +0200 |
commit | 0ccea881106946b66d167eee0ec8116ae4e3019e (patch) | |
tree | f5bdf7501d97cf31a767ed91335145530db4f49d /src/parsePost.ts | |
parent | 241ceeba4ad203b1e0711490344e970a3a452d07 (diff) | |
download | kronikarz-0ccea881106946b66d167eee0ec8116ae4e3019e.tar.gz kronikarz-0ccea881106946b66d167eee0ec8116ae4e3019e.zip |
Add parsePost
Diffstat (limited to 'src/parsePost.ts')
-rw-r--r-- | src/parsePost.ts | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/src/parsePost.ts b/src/parsePost.ts new file mode 100644 index 0000000..01e8d1c --- /dev/null +++ b/src/parsePost.ts @@ -0,0 +1,45 @@ +import * as fs from "fs"; +import { JSDOM } from "jsdom"; +import { Post, PostContent } from "./interfaces"; + +const frontmatter = require("front-matter"); +const md = require("markdown-it")(); + +function getDescription(html: string): string { + const { document } = new JSDOM(`<div>${html}</div>`).window; + const elements = document.getElementsByTagName("p"); + + const description = elements[1].textContent; + + return description || ""; +} + +function getPostContent(fileContent: string): PostContent { + const post = frontmatter(fileContent); + + const markdown = post.body; + const html = `<div>${md.render(markdown)}</div>`; + const description = getDescription(html); + + return { + html, + markdown, + description, + meta: post.attributes + }; +} + +export default function parsePost(filePath: string): Post { + const [year, month, day, title] = filePath.split("/").splice(-4, 4); + const date = { year, month, day }; + const fileContent = fs.readFileSync(filePath, "utf-8"); + const content = getPostContent(fileContent); + + return { + date, + title: title.substr(0, title.lastIndexOf(".")), + content, + filePath, + route: `/kronika/${year}/${month}/${day}/${title}` + }; +} |