|
| 1 | +import fs from "fs"; |
| 2 | +import path from "path"; |
| 3 | + |
| 4 | +import { request as graphQLRequest } from "graphql-request"; |
| 5 | +import { PluginOptions, Post } from "./types"; |
| 6 | +import { LoadContext } from "@docusaurus/types"; |
| 7 | + |
| 8 | +const query = ` |
| 9 | + query { |
| 10 | + posts { |
| 11 | + edges { |
| 12 | + node { |
| 13 | + id |
| 14 | + slug |
| 15 | + title |
| 16 | + date |
| 17 | + excerpt |
| 18 | + featuredImage { |
| 19 | + node { |
| 20 | + sourceUrl |
| 21 | + } |
| 22 | + } |
| 23 | + content |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | +`; |
| 29 | + |
| 30 | +function formatBlogDate(date: Date): String { |
| 31 | + var yyyy = date.getFullYear().toString(); |
| 32 | + var mm = (date.getMonth() + 1).toString(); |
| 33 | + var dd = date.getDate().toString(); |
| 34 | + |
| 35 | + var mmChars = mm.split(""); |
| 36 | + var ddChars = dd.split(""); |
| 37 | + |
| 38 | + return ( |
| 39 | + yyyy + |
| 40 | + "-" + |
| 41 | + (mmChars[1] ? mm : "0" + mmChars[0]) + |
| 42 | + "-" + |
| 43 | + (ddChars[1] ? dd : "0" + ddChars[0]) |
| 44 | + ); |
| 45 | +} |
| 46 | + |
| 47 | +export default function pluginWordpressToDocusaurus( |
| 48 | + context: LoadContext, |
| 49 | + options: PluginOptions |
| 50 | +) { |
| 51 | + const { outputPath = "blog", url } = options; |
| 52 | + return { |
| 53 | + name: "wordpress-docusaurus-blog-plugin", |
| 54 | + async loadContent() { |
| 55 | + const response = await graphQLRequest(url, query); |
| 56 | + const { edges } = response.posts; |
| 57 | + edges.forEach((post: Post) => { |
| 58 | + const { |
| 59 | + content, |
| 60 | + date: dateStr, |
| 61 | + excerpt, |
| 62 | + featuredImage, |
| 63 | + slug, |
| 64 | + title, |
| 65 | + } = post.node; |
| 66 | + const blogDate = new Date(dateStr); |
| 67 | + const blogFile = `${formatBlogDate(blogDate)}-${slug}.md`; |
| 68 | + const blogPath = path.resolve(context.siteDir, outputPath, blogFile); |
| 69 | + const blogContent = content |
| 70 | + .replace(/<br>/g, " \n") |
| 71 | + .replace(/<\/li>/g, "</li> \n") |
| 72 | + .replace(/<pre class="wp-block-code"><code>/g, "\n```\n") |
| 73 | + .replace(/<\/code><\/pre>/g, "\n```\n") |
| 74 | + .replace(/<p>/g, "") |
| 75 | + .replace(/<\/p>/g, " `\n"); |
| 76 | + const blogDoc = [ |
| 77 | + "---", |
| 78 | + `slug: ${slug}`, |
| 79 | + `title: ${title}`, |
| 80 | + "---", |
| 81 | + excerpt, |
| 82 | + featuredImage |
| 83 | + ? `<img src="${featuredImage.node.sourceUrl}" />\n` |
| 84 | + : null, |
| 85 | + "<!--truncate-->", |
| 86 | + blogContent, |
| 87 | + ].join("\n"); |
| 88 | + fs.writeFile(blogPath, blogDoc, function (err) { |
| 89 | + if (err) throw err; |
| 90 | + console.log(`Created Blog ${blogPath}`); |
| 91 | + }); |
| 92 | + }); |
| 93 | + }, |
| 94 | + }; |
| 95 | +} |
0 commit comments