summary refs log tree commit diff
path: root/src/index.ts
blob: b6a2b78d2879ddf87a48773702d9b3658d1e7557 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import * as fs from "fs";
import { JSDOM } from "jsdom";

const frontmatter = require("front-matter");
const md = require("markdown-it")();

const POSTS_PATH = "./content/wpisy";

interface Date {
  year: string;
  month: string;
  day: string;
}

interface Post {
  date: Date;
  title: string;
  data: Object;
  file: string;
  fsRoute: string;
  route: string;
}

function getPostAttributes(fileContent: string) {
  const post = frontmatter(fileContent);

  const { document } = new JSDOM(`<body>${md.render(post.body)}</body>`).window;
  const element = document.getElementsByTagName("p");

  post.body = `<div>${md.render(post.body)}</div>`;
  post.description = element[1].textContent;

  return post;
}

function getPosts() {
  let routesArray: Post[] = [];
  try {
    const years = fs.readdirSync(`${POSTS_PATH}`);
    years.forEach((year: string) => {
      const months = fs.readdirSync(`${POSTS_PATH}/${year}`);
      months.forEach((month: string) => {
        const days = fs.readdirSync(`${POSTS_PATH}/${year}/${month}`);
        days.forEach((day: string) => {
          const files = fs.readdirSync(`${POSTS_PATH}/${year}/${month}/${day}`);
          files.forEach((file: string) => {
            const title = file.substr(0, file.lastIndexOf("."));
            const route = `/kronika/${year}/${month}/${day}/${title}/`;
            const fsRoute = `${POSTS_PATH}/${year}/${month}/${day}/${file}`;

            const data = getPostAttributes(fs.readFileSync(fsRoute, "utf-8"));

            const post = {
              date: { year, month, day },
              title,
              data,
              file,
              fsRoute,
              route
            };

            routesArray.push(post);
          });
        });
      });
    });
  } finally {
    return routesArray;
  }
}

function createRoutesArray() {
  let posts = getPosts();
  return posts.map(post => post.route);
}

export { getPosts, createRoutesArray, getPostAttributes };