test.js 1.2 KB
"use strict";

/**
 * test controller
 */

const { createCoreController } = require("@strapi/strapi").factories;
const { parseMultipartData, sanitizeEntity } = require("@strapi/utils");

module.exports = createCoreController("api::test.test", () => ({
  async create(ctx) {
    let entity;

    if (ctx.request.is("multipart/form-data")) {
      const { body: data, files } = ctx.request;
      console.log("Data:", data);
      console.log("Files:", files);

      // Ensure imgComponent structure
      if (data.imgComponent && Array.isArray(data.imgComponent)) {
        data.imgComponent = data.imgComponent.map((item, index) => ({
          ...item,
          image: files[`imgComponent[${index}].image`], // Ensure correct structure
        }));
      }
      console.log("final", data.data, files);
      try {
        entity = await strapi.entityService.create("api::test.test", {
          data,
          files,
        });
        console.log("entity, ", entity);
        return ctx.send({ payload: entity, success: true });
      } catch (error) {
        console.error(error);
        ctx.throw(500, error.message);
      }
    } else {
      ctx.throw(400, "Request must be multipart/form-data");
    }
  },
}));