Skip to content

Instantly share code, notes, and snippets.

@kvnol
Last active April 16, 2024 17:29
Show Gist options
  • Save kvnol/8492e38a98f428f210fa0479dec18007 to your computer and use it in GitHub Desktop.
Save kvnol/8492e38a98f428f210fa0479dec18007 to your computer and use it in GitHub Desktop.
Migrating WordPress to Strapi V4

Migrating WordPress to Strapi V4

Example using albums post type, change for your post type.

Route

/* src/api/albums/routes/01-import.js */

module.exports = {
  routes: [
    {
      method: "GET",
      path: "/albums/import",
      handler: "album.import",
      config: {
        policies: [],
      },
    },
  ],
};

Controller

/* src/api/album/controllers/album.js */

"use strict";

/**
 *  album controller
 */

const { createCoreController } = require("@strapi/strapi").factories;
const axios = require("axios");
const fs = require("fs").promises;

module.exports = createCoreController("api::album.album", ({ strapi }) => ({
  import: async (ctx) => {
    const { data } = await axios.get(
      "https://your-site.com.br/wp-json/wp/v2/album?per_page=1"
    );
    const albums = await Promise.all(
      data.map(
        (album) =>
          new Promise(async (resolve, reject) => {
            const {
              title: { rendered: titleRendered },
              content: { rendered: contentRendered },
            } = album;

            try {
              const downloaded = await strapi
                .service("api::album.download")
                .download(imageRendered);

              const [{ id: fileId }] = await strapi
                .service("api::album.upload")
                .upload(downloaded);

              const created = await strapi.entityService.create(
                "api::album.album",
                {
                  data: {
                    title: titleRendered,
                    content: contentRendered,
                  },
                }
              );
              resolve(created);
            } catch (err) {
              reject(err);
            }
          })
      )
    );

    ctx.send(albums);
  },
}));

Services

  1. npx strapi generate
  2. select service

Download

"use strict";

const axios = require("axios");
const path = require("path");
const fs = require("fs");

/**
 * download service.
 */

module.exports = {
  download: async (url) => {
    // get the filename such as `image01.jpg`
    const name = path.basename(url);
    // we need to set a file path on our host where the image will be
    // downloaded to
    const filePath = `/tmp/${name}`;
    // create an instance of fs.writeStream
    const writeStream = fs.createWriteStream(filePath);
    // make a GET request and create a readStream to the resource
    const { data } = await axios.get(url, { responseType: "stream" });

    // pipe the data we receive to the writeStream
    data.pipe(writeStream);
    // return a new Promise that resolves when the event writeStream.on
    // is emitted. Resolves the file path
    return new Promise((resolve, reject) => {
      writeStream.on("finish", () => {
        resolve(filePath);
      });
      writeStream.on("error", reject);
    });
  },
};

Upload

"use strict";

const path = require("path");
const fs = require("fs").promises;

/**
 * upload service.
 */

module.exports = {
  upload: async (imgPath) => {
    const buffer = await fs.readFile(imgPath);
    const name = path.basename(imgPath);
    const ext = path.extname(imgPath).slice(1);

    return await strapi.plugins.upload.services.upload.upload({
      data: {},
      files: {
        path: imgPath,
        name: name,
        type: `image/${ext}`, // mime type of the file
        size: buffer.toString().length,
      },
    });
  },
};

Run GET to http://localhost:1337/api/albums/import on Postman.

Refs:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment