site/gatsby-node.js

113 lines
3.1 KiB
JavaScript
Raw Normal View History

const path = require('path')
2020-08-24 14:46:46 +03:00
const ncp = require('ncp').ncp;
2020-08-24 14:46:46 +03:00
const filesSource = "./src/files"
const imagesSource = "./src/images"
exports.onPreBootstrap = () => {
ncp(filesSource, "./static/files", function (err) {
if (err) {
return console.error(err);
}
console.log('Files copied');
});
ncp(imagesSource, "./static/images", function (err) {
if (err) {
return console.error(err);
}
console.log('Images copied');
});
}
exports.createPages = async ({actions, graphql}) => {
const {createPage} = actions;
2020-08-24 14:46:46 +03:00
// language=GraphQL
const result = await graphql(`
2020-08-24 14:46:46 +03:00
{
2021-03-28 21:32:20 +03:00
news: allMarkdownRemark(
filter: {frontmatter: {content_type: {eq: "post"}, published: {ne: false}}},
sort: {fields: [frontmatter___date], order: DESC}
) {
edges{
node{
frontmatter{
title
2021-03-28 21:32:20 +03:00
slug
date(formatString: "DD.MM.YYYY")
}
2021-03-28 21:32:20 +03:00
html
}
}
}
2020-08-24 14:46:46 +03:00
2021-03-28 21:32:20 +03:00
coursePages: allMarkdownRemark(
filter: {frontmatter: {content_type: {eq: "course"}, published: {ne: false}}}
){
2020-08-24 14:46:46 +03:00
edges{
node{
2021-03-28 21:32:20 +03:00
html
2020-08-24 14:46:46 +03:00
frontmatter{
2021-03-28 21:32:20 +03:00
path
2020-08-24 14:46:46 +03:00
slug
}
}
}
}
2021-03-28 21:32:20 +03:00
}
`)
2020-08-24 14:46:46 +03:00
if (result.errors) {
throw result.errors;
}
2021-03-28 21:32:20 +03:00
// Render courses
const courseTemplate = path.resolve(`./src/components/templates/courseTemplate.js`);
2021-03-28 21:32:20 +03:00
const courses = result.data.coursePages.edges;
courses.forEach(({node}) => {
createPage({
path: node.frontmatter.path,
component: courseTemplate,
})
});
2021-03-28 21:32:20 +03:00
// Render news page
const newsTemplate = path.resolve(`./src/components/templates/news.js`);
const posts = result.data.news.edges;
2020-08-24 14:46:46 +03:00
const postsPerPage = 5;
const numberOfNewsItems = posts.length;
const numberOfNewsPages = Math.ceil(numberOfNewsItems / postsPerPage);
2020-08-24 14:46:46 +03:00
for (let pageIndex = 0; pageIndex < numberOfNewsPages; pageIndex++) {
2020-08-24 14:46:46 +03:00
const pageNumber = pageIndex + 1;
const path = pageIndex === 0 ? '/news' : `/news/${pageNumber}`;
const skip = pageIndex * postsPerPage;
function getPreviousPageLink() {
if (!pageIndex) return null
if (pageIndex === 1) return '/news'
return `/news/${pageIndex}`
}
function getNextPageLink() {
if (pageNumber < numberOfNewsPages) return `news/${pageNumber + 1}`
return null
}
createPage({
path,
component: newsTemplate,
context: {
limit: postsPerPage,
skip,
next: getNextPageLink(),
prev: getPreviousPageLink(),
},
})
}
}