|
| 1 | +const axios = require('axios'); |
| 2 | +const crypto = require("crypto"); |
| 3 | + |
| 4 | +HASHNODE_API_URL = 'https://api.hashnode.com/'; |
| 5 | + |
| 6 | +async function getCuidsForAllPosts(username) { |
| 7 | + let query = `query{ user(username: "` + username + `") {publication {posts { cuid }}}}`; |
| 8 | + let { data } = await axios.post(HASHNODE_API_URL, { query: query }); |
| 9 | + let publication = data.data.user.publication; |
| 10 | + |
| 11 | + if (!publication) { |
| 12 | + throw new Error('No publications found for this user.'); |
| 13 | + } |
| 14 | + |
| 15 | + let posts = publication.posts; |
| 16 | + |
| 17 | + let allCuids = [] |
| 18 | + for (let post of posts) { |
| 19 | + allCuids.push(post.cuid); |
| 20 | + } |
| 21 | + |
| 22 | + return allCuids; |
| 23 | +} |
| 24 | + |
| 25 | +function getQueryForSinglePostDetail(cuid) { |
| 26 | + return cuid + `:` + `post(cuid: "` + cuid + `") { cuid slug title type dateUpdated dateAdded contentMarkdown content brief coverImage tags { name }}`; |
| 27 | +} |
| 28 | + |
| 29 | +async function getAllPostDetails(allCuids) { |
| 30 | + if (!allCuids.length) { |
| 31 | + console.warn('No posts found in the devblog.'); |
| 32 | + return []; |
| 33 | + } |
| 34 | + |
| 35 | + let query = `query{`; |
| 36 | + |
| 37 | + for (let cuid of allCuids) { |
| 38 | + query += getQueryForSinglePostDetail(cuid); |
| 39 | + } |
| 40 | + |
| 41 | + query += '}'; |
| 42 | + |
| 43 | + let { data } = await axios.post(HASHNODE_API_URL, { query: query }); |
| 44 | + data = data.data; |
| 45 | + |
| 46 | + let posts = []; |
| 47 | + |
| 48 | + for (let postCuid in data) { |
| 49 | + posts.push(data[postCuid]); |
| 50 | + } |
| 51 | + |
| 52 | + return posts; |
| 53 | +} |
| 54 | + |
| 55 | +exports.sourceNodes = async ({ actions }, options) => { |
| 56 | + if (!options.username) { |
| 57 | + throw new Error('Missing username option.') |
| 58 | + } |
| 59 | + |
| 60 | + const { createNode } = actions; |
| 61 | + |
| 62 | + const allCuids = await getCuidsForAllPosts(options.username); |
| 63 | + const posts = await getAllPostDetails(allCuids); |
| 64 | + |
| 65 | + for (let post of posts) { |
| 66 | + const jsonString = JSON.stringify(post); |
| 67 | + |
| 68 | + const gatsbyNode = { |
| 69 | + post: Object.assign({}, post), |
| 70 | + id: `${post.cuid}`, |
| 71 | + parent: "__SOURCE__", |
| 72 | + children: [], |
| 73 | + internal: { |
| 74 | + type: 'devblogPost', |
| 75 | + contentDigest: crypto |
| 76 | + .createHash("md5") |
| 77 | + .update(jsonString) |
| 78 | + .digest("hex") |
| 79 | + } |
| 80 | + }; |
| 81 | + |
| 82 | + createNode(gatsbyNode); |
| 83 | + } |
| 84 | +} |
0 commit comments