|
| 1 | +/** |
| 2 | + * Add a tag to every post |
| 3 | + * |
| 4 | + * Note: Assumes you already have the tag created |
| 5 | + * |
| 6 | + * Usage: |
| 7 | + * |
| 8 | + * node add-tag-to-all-posts.js https://blah.ghost.io ADMIN_API_KEY slug-of-tag-to-add |
| 9 | + */ |
| 10 | + |
| 11 | +if (process.argv.length < 5) { |
| 12 | + console.error('Missing an argument'); |
| 13 | + process.exit(1); |
| 14 | +} |
| 15 | + |
| 16 | +const url = process.argv[2]; |
| 17 | +const key = process.argv[3]; |
| 18 | +const tag = process.argv[4]; |
| 19 | + |
| 20 | +const Promise = require('bluebird'); |
| 21 | +const GhostAdminAPI = require('@tryghost/admin-api'); |
| 22 | +const api = new GhostAdminAPI({ |
| 23 | + url, |
| 24 | + key, |
| 25 | + version: 'v2' |
| 26 | + }); |
| 27 | + |
| 28 | +(async function main() { |
| 29 | + try { |
| 30 | + console.log(`Adding tag ${tag} to ${url}`); |
| 31 | + |
| 32 | + const tagToAdd = await api.tags.read({ slug: tag }); |
| 33 | + |
| 34 | + console.log('Found tag', tagToAdd); |
| 35 | + |
| 36 | + // Admin API automatically includes tags and authors |
| 37 | + // WARNING: If the site is really big (1000s of posts) maybe do this paginated |
| 38 | + const allPosts = await api.posts.browse({ limit: 'all' }); |
| 39 | + |
| 40 | + // convert our list of posts, to a list of promises for requests to the api |
| 41 | + const result = await Promise.mapSeries(allPosts, async (post) => { |
| 42 | + |
| 43 | + // Add the tag to the post |
| 44 | + post.tags.push(tagToAdd); |
| 45 | + |
| 46 | + // Weird.. we shouldn't need to do this: |
| 47 | + delete post.uuid; |
| 48 | + delete post.comment_id; |
| 49 | + |
| 50 | + console.log('Updating', post.slug); |
| 51 | + // Call the API |
| 52 | + let result = await api.posts.edit(post); |
| 53 | + |
| 54 | + // Add a delay but return the original result |
| 55 | + return Promise.delay(50).return(result); |
| 56 | + }); |
| 57 | + |
| 58 | + console.log(`Updated ${result.length} posts`); |
| 59 | + |
| 60 | + } catch (err) { |
| 61 | + console.error('There was an error', require('util').inspect(err, false, null)); |
| 62 | + process.exit(1); |
| 63 | + } |
| 64 | +}()); |
0 commit comments