gatsby-plugin-social-cards
Version:
Generates social cards for your markdown posts and adds a field so you can reference them in your meta-tags.
60 lines (52 loc) • 1.73 kB
JavaScript
const generateCard = require("./build").generateCard;
const path = require("path");
const fs = require("fs-extra");
function base64file(path) {
const b64 = fs.readFileSync(path, "base64");
return `data:image/jpeg;base64,${b64}`;
}
exports.onCreateNode = ({ node, getNode, actions, graphql }, options) => {
const { createNodeField } = actions;
if (node.internal.type === `MarkdownRemark` || node.internal.type === `Mdx`) {
const { frontmatter } = node;
let authorImage64;
if (options.authorImage && fs.existsSync(options.authorImage)) {
authorImage64 = base64file(options.authorImage);
}
let cover = options.backgroundImage;
if (frontmatter.cover) {
const { dir } = getNode(node.parent);
cover = path.join(dir, frontmatter.cover);
}
const filename = "gatsby-plugin-social-card/" + node.id + ".jpg";
const output = path.join("./public", filename);
fs.ensureFileSync(output);
const author = frontmatter.author || options.defaultAuthor;
const subtitle = author ? `by ${author}` : "";
generateCard(
{
title: frontmatter.title,
subtitle,
backgroundImage: cover,
design: options.design,
authorImage64,
},
output
)
.then(() => {
console.log(frontmatter.title, "generated: " + output);
try {
createNodeField({
node,
name: `socialcard`,
value: filename,
});
} catch (err) {
console.error("createNodeField failed");
}
})
.catch((err) => {
console.error("ERROR while generating card", err);
});
}
};