Blame view

src/api/test/controllers/test.js 1.2 KB
jaymehta committed
1
"use strict";
jaymehta committed
2 3 4 5 6

/**
 * test controller
 */

jaymehta committed
7 8
const { createCoreController } = require("@strapi/strapi").factories;
const { parseMultipartData, sanitizeEntity } = require("@strapi/utils");
jaymehta committed
9

jaymehta committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
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");
    }
  },
}));