1
0
mirror of https://github.com/kremalicious/blog.git synced 2024-11-23 02:10:01 +01:00
blog/gatsby/createMarkdownFields.js

57 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-10-14 02:25:24 +02:00
const path = require('path')
const { createFilePath } = require('gatsby-source-filesystem')
2018-11-18 23:11:36 +01:00
const { repoContentPath } = require('../config')
2018-10-14 02:25:24 +02:00
// Create slug, date & github file link for posts from file path values
exports.createMarkdownFields = (node, actions, getNode) => {
const { createNodeField } = actions
const fileNode = getNode(node.parent)
const parsedFilePath = path.parse(fileNode.relativePath)
const slugOriginal = createFilePath({ node, getNode })
2019-11-26 00:06:29 +01:00
createSlug(node, createNodeField, parsedFilePath)
createDate(node, createNodeField, slugOriginal)
// github file link
const type = fileNode.sourceInstanceName
const file = fileNode.relativePath
const githubLink = `${repoContentPath}/${type}/${file}`
createNodeField({
node,
name: 'githubLink',
value: githubLink
})
}
2019-11-26 00:06:29 +01:00
function createSlug(node, createNodeField, parsedFilePath) {
2018-10-14 02:25:24 +02:00
let slug
if (parsedFilePath.name === 'index') {
slug = `/${parsedFilePath.dir.substring(11)}` // remove date from file dir
} else {
2019-11-26 00:06:29 +01:00
slug = `/${parsedFilePath.name.substring(11)}` // remove date from file path
2018-10-14 02:25:24 +02:00
}
createNodeField({
node,
name: 'slug',
value: slug
})
2019-10-02 13:35:50 +02:00
}
2018-10-14 02:25:24 +02:00
2019-10-02 13:35:50 +02:00
function createDate(node, createNodeField, slugOriginal) {
2019-02-03 21:18:59 +01:00
// grab date from file path
let date = new Date(slugOriginal.substring(1, 11)).toISOString() // grab date from file path
2018-10-14 02:25:24 +02:00
if (node.frontmatter.date) {
2019-02-03 21:18:59 +01:00
date = new Date(node.frontmatter.date).toISOString()
2018-10-14 02:25:24 +02:00
}
createNodeField({
node,
name: 'date',
value: date
})
2019-10-02 13:35:50 +02:00
}