Skip to content
Snippets Groups Projects
init-ghost.js 6.56 KiB
Newer Older
  • Learn to ignore specific revisions
  • // eslint-disable-next-line @typescript-eslint/no-var-requires
    const _ = require('lodash');
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const tagsData = require('./ghost/migrations/init/tags.json');
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const postsData = require('./ghost/migrations/init/posts.json');
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    
    const pagesData = require('./ghost/migrations/init/pages.json');
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    
    const path = require('path');
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const GhostAdminAPI = require('@tryghost/admin-api');
    
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
    
    var api = new GhostAdminAPI({
      url: process.env.GHOST_HOST_AND_PORT,
      key: process.env.GHOST_ADMIN_API_KEY,
      version: 'v3',
    });
    
    async function deleteTags(existingTags) {
      return await Promise.all(
        _.forEach(existingTags, async (tag) => {
    
            .delete(_.pick(tag, ['id']))
            .then((res) => {
              return null;
            })
            .catch((error) => console.error(error));
        })
      );
    }
    async function deletePosts(existingPosts) {
      return await Promise.all(
        _.forEach(existingPosts, async (tag) => {
    
            .delete(_.pick(tag, ['id']))
            .then((res) => {
              return null;
            })
            .catch((error) => console.error(error));
        })
      );
    }
    
    async function deletePages(existingPages) {
      return await Promise.all(
        _.forEach(existingPages, async (id) => {
          await api.pages
            .delete(_.pick(id, ['id']))
            .then((res) => {
              return null;
            })
            .catch((error) => console.error(error));
        })
      );
    }
    
    
    async function createTags(deleteOnly) {
      // Get existing tags
      await api.tags
        .browse({ limit: 'all' })
        .then(async (existingTags) => {
          // remove 'meta' key
          delete existingTags['meta'];
          if (existingTags.length > 0) {
            console.log('-- Dropping ' + existingTags.length + ' tags... --');
            // Delete existing tags
            await deleteTags(existingTags).then(() => {
              console.log('-- Tags dropped --');
            });
          } else {
            console.log('-- No tag to drop --');
          }
    
          // Creating new tags
          if (!deleteOnly) {
            console.log('-- Creating ' + tagsData.tags.length + ' tags --');
            _.forEach(tagsData.tags, (tag) => {
              api.tags
                .add(tag)
                .then((res) => {
                  console.log('-- Tag `' + res.name + '` created --');
                })
                .catch((error) => console.error(error));
            });
          }
        })
        .catch((error) => console.error(error));
    }
    
    // Utility function to find and upload any images in an HTML string
    function processImagesInHTML(html) {
      // Find images that Ghost Upload supports
      let imageRegex = /="([^"]*?(?:\.jpg|\.jpeg|\.gif|\.png|\.svg|\.sgvz))"/gim;
      let imagePromises = [];
    
      while ((result = imageRegex.exec(html)) !== null) {
    
        let file = result[1];
        // Upload the image, using the original matched filename as a reference
        imagePromises.push(
          api.images.upload({
            ref: file,
            file: path.resolve(file),
          })
        );
      }
    
      return Promise.all(imagePromises).then((images) => {
        images.forEach((image) => (html = html.replace(image.ref, image.url)));
        return html;
      });
    }
    
    
      let imagePromise = api.images.upload({
    
      return Promise.resolve(imagePromise)
        .then((url) => {
    
        .catch((error) => {
          console.error(error);
          return null;
        });
    
    async function createPosts(deleteOnly) {
      api.posts
        .browse({ limit: 'all' })
        .then(async (existingPosts) => {
          // remove 'meta' key
          delete existingPosts['meta'];
          if (existingPosts.length > 0) {
            console.log('-- Dropping ' + existingPosts.length + ' posts... --');
            // Delete existing posts
            await deletePosts(existingPosts).then(() => {
              console.log('-- Posts dropped --');
            });
          } else {
            console.log('-- No posts to drop --');
          }
    
          // Creating new posts
          if (!deleteOnly) {
            console.log('-- Creating ' + postsData.length + ' posts --');
    
            _.forEach(postsData, async (post) => {
              //upload de l'image en featured_image
              if (post.feature_image) {
                post.feature_image = await uploadPostImage(post.feature_image);
              }
    
              api.posts
                .add(post, { source: 'html' })
                .then((res) => {
                  console.log('-- Post `' + res.title + '` created --');
                })
                .catch((error) => console.error(error));
            });
          }
        })
        .catch((error) => console.error(error));
    }
    
    
    async function createPages(deleteOnly) {
      api.pages
        .browse({ limit: 'all' })
        .then(async (existingPages) => {
          // remove 'meta' key
          delete existingPages['meta'];
          if (existingPages.length > 0) {
            console.log(`-- Dropping ${existingPages.length} pages... --`);
            // Delete existing pages
            await deletePages(existingPages).then(() => {
              console.log('-- Pages dropped --');
            });
          } else {
            console.log('-- No pages to drop --');
          }
          // wait complete delete of pages, if not page slugs are appended by _2
          await new Promise((r) => setTimeout(r, 1000));
    
          // Creating new pages
          if (!deleteOnly) {
            console.log(`-- Creating ${pagesData.length} pages --`);
            _.forEach(pagesData, async (page) => {
              //upload de l'image en featured_image
              if (page.feature_image) {
                page.feature_image = await uploadPostImage(page.feature_image);
              }
              api.pages
                .add(page, { source: 'html' })
                .then((res) => {
                  console.log(`-- Page \`${res.title}\` created --`);
                })
                .catch((error) => console.error(error));
            });
          }
        })
        .catch((error) => console.error(error));
    }
    
    
    async function main(deleteOnly) {
    
      createTags(deleteOnly)
        .then(() => {
          createPosts(deleteOnly);
        })
        .then(() => {
          createPages(deleteOnly);
        });
    
    }
    
    var myArgs = process.argv.slice(2);
    
    switch (myArgs[0]) {
      case 'drop':
        console.log('-- Droping data --');
        main(true);
        break;
      case 'up':
        console.log('-- Init db --');
        main(false);
        break;
      default:
        console.error('Unknown cmd');
    }