about summary refs log tree commit diff stats
path: root/src/modules/posts.js
blob: cf2d80e7ef5195bdfa9e69e0708ae58bf6fdaee1 (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
78
79
80
81
82
83
84
85
86
87
88
'use strict'

const fs = require('fs')
const path = require('path')
const matter = require('gray-matter')
const Markdown = require('markdown-it')

const grayMatterOptions = {
  lang: 'toml',
  delims: '+++'
}

const markdownOptions = {
  html: true,
  typographer: true
}

const markdown = new Markdown(markdownOptions)

function* lowercaseKeys (iterator) {
  for (let [k, v] of iterator) {
    yield [String(k).toLowerCase(), v]
  }
}

function canonicaliseMetadata (meta) {
  if (meta.data) {
    meta.data = new Map(lowercaseKeys(Object.entries(meta.data)))
  } else {
    meta.data = new Map()
  }
  return meta
}

function getTitle (file) {
  return path.basename(file.path, path.extname(file.path))
}

function render (post) {
  return markdown.render(post.content)
}

function get (filename) {
  const fileMatter = matter.read(filename, grayMatterOptions)
  fileMatter.basename = getTitle(fileMatter)
  return canonicaliseMetadata(fileMatter)
}

function getFolder (folder) {
  return new Map(
    fs
      .readdirSync(folder)
      .map(f => path.resolve(folder, f))
      .map(get)
      .map(f => [getTitle(f), f])
  )
}

function taxonomise (taxonomies, posts) {
  const taxons = new Map(Object.keys(taxonomies).map(t => [t, new Map()]))

  for (let [, post] of posts) {
    for (let [singularName, pluralName] of Object.entries(taxonomies)) {
      if (post.data.has(pluralName)) {
        for (let term of post.data.get(pluralName)) {
          const current = taxons.get(singularName).get(term)
          taxons
            .get(singularName)
            .set(term, current ? current.concat(post) : [post])
        }
      }
    }
  }

  return taxons
}

function toTags (posts) {
  return taxonomise({ tag: 'tags' }, posts).get('tag')
}

module.exports = {
  get,
  getFolder,
  toTags,
  taxonomise,
  render
}