diff options
author | Patryk Niedźwiedziński <pniedzwiedzinski19@gmail.com> | 2020-01-28 11:55:03 +0100 |
---|---|---|
committer | Patryk Niedźwiedziński <pniedzwiedzinski19@gmail.com> | 2020-01-28 11:55:03 +0100 |
commit | 9f75ff1d2d5ebf34c040474e836e125f80253365 (patch) | |
tree | 523c52b9dd158e21d9247b58d81c655102323a26 /lib/Post.ts | |
parent | c11d7a84aa59e9b1179a9834129b2d776bab8bca (diff) | |
download | kronikarz-9f75ff1d2d5ebf34c040474e836e125f80253365.tar.gz kronikarz-9f75ff1d2d5ebf34c040474e836e125f80253365.zip |
Add Post class
Diffstat (limited to 'lib/Post.ts')
-rw-r--r-- | lib/Post.ts | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/lib/Post.ts b/lib/Post.ts new file mode 100644 index 0000000..27a6cb9 --- /dev/null +++ b/lib/Post.ts @@ -0,0 +1,70 @@ +import * as fs from 'fs'; +import { JSDOM } from 'jsdom'; + +const frontmatter = require('front-matter'); +const md = require('markdown-it')(); + +import { dateToPath, dateToString } from './utils'; +import { Date, FrontMatterObject, PostApiEntry, Meta } from './interfaces'; + +export default class Post { + date: Date; + fileTitle: string; + fileContent: string; + post: FrontMatterObject; + + constructor(filePath: string) { + let [year, month, day, title] = filePath.split('/').splice(-4, 4); + this.fileTitle = title.substr(0, title.lastIndexOf('.')); + this.date = { year, month, day }; + this.fileContent = fs.readFileSync(filePath, 'utf-8'); + this.post = frontmatter(this.fileContent); + } + + toApi(): PostApiEntry { + const { author, title, additionalMeta } = this.getMeta(); + const { description, html } = this.getPostContent(); + return { + date: dateToString(this.date), + author, + title, + path: `/kronika/${dateToPath(this.date)}/${this.fileTitle}`, + description, + meta: additionalMeta, + content: html, + }; + } + + getMeta(): Meta { + const { attributes } = this.post; + const author: string = attributes.author; + delete attributes.author; + const title: string = attributes.title; + delete attributes.title; + return { + author, + title, + additionalMeta: attributes, + }; + } + + getPostContent() { + const { body } = this.post; + const html = `<div>${md.render(body)}</div>`; + const description = this.getDescription(html); + + return { + html, + description, + }; + } + + getDescription(html: string): string { + const { document } = new JSDOM(`<div>${html}</div>`).window; + const elements = document.getElementsByTagName('p'); + + const description = elements[1].textContent; + + return description || ''; + } +} |