|
| 1 | +import fsUtils from '@tryghost/mg-fs-utils'; |
| 2 | +import GhostAdminAPI from '@tryghost/admin-api'; |
| 3 | +import {makeTaskRunner} from '@tryghost/listr-smart-renderer'; |
| 4 | +import _ from 'lodash'; |
| 5 | +import {discover} from '../lib/batch-ghost-discover.js'; |
| 6 | + |
| 7 | +const initialise = (options) => { |
| 8 | + return { |
| 9 | + title: 'Initialising API connection', |
| 10 | + task: (ctx, task) => { |
| 11 | + let defaults = { |
| 12 | + verbose: false, |
| 13 | + tag: false, |
| 14 | + author: false, |
| 15 | + delayBetweenCalls: 50 |
| 16 | + }; |
| 17 | + |
| 18 | + const url = options.apiURL.replace(/\/$/, ''); |
| 19 | + const key = options.adminAPIKey; |
| 20 | + const api = new GhostAdminAPI({ |
| 21 | + url: url.replace('localhost', '127.0.0.1'), |
| 22 | + key, |
| 23 | + version: 'v5.0' |
| 24 | + }); |
| 25 | + |
| 26 | + ctx.fileCache = new fsUtils.FileCache(options.apiURL); |
| 27 | + ctx.args = _.mergeWith(defaults, options); |
| 28 | + ctx.api = api; |
| 29 | + ctx.posts = []; |
| 30 | + ctx.found = 0; |
| 31 | + |
| 32 | + task.output = `Workspace initialised at ${ctx.fileCache.cacheDir}`; |
| 33 | + } |
| 34 | + }; |
| 35 | +}; |
| 36 | + |
| 37 | +const getFullTaskList = (options) => { |
| 38 | + return [ |
| 39 | + initialise(options), |
| 40 | + { |
| 41 | + title: 'Fetch Post Content from Ghost API', |
| 42 | + task: async (ctx, task) => { |
| 43 | + let postDiscoveryOptions = { |
| 44 | + api: ctx.api, |
| 45 | + type: 'posts', |
| 46 | + limit: 100, |
| 47 | + include: 'tags,authors', |
| 48 | + progress: (options.verbose) ? true : false |
| 49 | + }; |
| 50 | + |
| 51 | + try { |
| 52 | + ctx.posts = await discover(postDiscoveryOptions); |
| 53 | + task.output = `Found ${ctx.posts.length} posts`; |
| 54 | + } catch (error) { |
| 55 | + ctx.errors.push(error); |
| 56 | + throw error; |
| 57 | + } |
| 58 | + } |
| 59 | + }, |
| 60 | + { |
| 61 | + title: 'Saving as JSON file', |
| 62 | + task: async (ctx) => { |
| 63 | + await ctx.fileCache.saveFile(`${ctx.fileCache.tmpDir}/posts.json`, JSON.stringify({posts: ctx.posts}, null, 2)); |
| 64 | + ctx.found = ctx.posts.length; |
| 65 | + } |
| 66 | + } |
| 67 | + ]; |
| 68 | +}; |
| 69 | + |
| 70 | +const getTaskRunner = (options) => { |
| 71 | + let tasks = []; |
| 72 | + |
| 73 | + tasks = getFullTaskList(options); |
| 74 | + |
| 75 | + return makeTaskRunner(tasks, Object.assign({topLevel: true}, options)); |
| 76 | +}; |
| 77 | + |
| 78 | +export default { |
| 79 | + initialise, |
| 80 | + getFullTaskList, |
| 81 | + getTaskRunner |
| 82 | +}; |
0 commit comments