From 770dbb08501ff634199712f2f9a8944071570ba8 Mon Sep 17 00:00:00 2001 From: Hippo Date: Tue, 10 Dec 2019 18:15:09 +0530 Subject: [PATCH] Implement "fetch-medium" function No processing yet, but at least we get the post and metadata in a standard format --- functions.js | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++-- index.js | 9 ++++++--- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/functions.js b/functions.js index 669ed26..2471beb 100644 --- a/functions.js +++ b/functions.js @@ -1,13 +1,62 @@ const r2 = require('r2') +const path = require('path') +const fs = require('fs') const getPost = require('mediumexporter').getPost /** * function [fetchFromMedium] * @returns [string] status */ + const fetchFromMedium = async (mediumUrl) => { - console.debug('Fetching: ' + mediumUrl); - return await getPost(mediumUrl, { returnObject: true }) + console.info(`Fetching: ${mediumUrl}`); + output = path.join(process.env.PWD, 'content') + + // use mediumexporter's getPost function to fetch a Medium post + const post = await getPost(mediumUrl, { + returnObject: true, + output: output, + }).catch((err) => { + return { + error: err, + } + }) + + // set output folder path + // this is based on what mediumexporter chooses as the output folder + outputFolder = path.join(output, post.slug) + + console.info(`Saving to: ${outputFolder}`) + + if (!fs.existsSync(path.join(outputFolder, post.slug))) { + fs.mkdirSync(outputFolder, { recursive: true }) + } + + // mediumexporter writes a plain .md file if the post has no media + // if that is the case, we should create the subfolder manually + // and copy the data there. + if (fs.existsSync(path.join(output, post.slug + '.md'))) { + fs.renameSync( + path.join(output, post.slug + '.md'), + path.join(outputFolder, 'index.md') + ) + } + + // generate metadata + const metadata = JSON.stringify({ + title: post.title, + subtitle: post.subtitle, + date: new Date(post.date), + tags: post.tags, + url: post.url, + slug: post.slug, + images: post.images, + featuredImage: post.featuredImage, + }) + + // write metadata to output folder + fs.writeFileSync(path.join(outputFolder, 'metadata.json')) + return post }; /** diff --git a/index.js b/index.js index 8d449a2..546ee6b 100755 --- a/index.js +++ b/index.js @@ -19,8 +19,7 @@ program.command('fetch-medium ') .action((post_url) => { fetchFromMedium(post_url) .then((post) => { - console.info(`"${post.title}" fetched successfully`) - console.debug(post) + console.info(`"${post.title}" fetched successfully.`) }) }); @@ -41,7 +40,11 @@ program.command('medium-to-ghost ') program.command('create-user ') .description('create ghost-import.json to import Medium user to Ghost') .action(async (username, email) => { - const jsonOut = await generateUserData(username, email); + const jsonOut = await generateUserData(username, email) + .catch((err) => { + console.log(`Error: ${err.error}`) + return + }) console.log(await jsonOut); });