Coder Social home page Coder Social logo

[BUG] DOCs not right for PRODUCT API about evershop HOT 2 OPEN

el-j avatar el-j commented on May 31, 2024
[BUG] DOCs not right for PRODUCT API

from evershop.

Comments (2)

evershopcommerce avatar evershopcommerce commented on May 31, 2024 1

Hi @el-j ,

We are working on the file storage with some change to the way of storing product images. We will update the docs soon. Thanks

from evershop.

el-j avatar el-j commented on May 31, 2024

hi, in the meantime i have written my self a little extension, that looks into the images and if they are an url, it downloads the images and puts them to the normal process. so thumbnails and everything gets created as needed.

const https = require("https");
const { createWriteStream, unlink } = require("fs");
async function download(url, dest) {
  console.log("url", url, "dest", dest);
  var file = createWriteStream(dest);
  return new Promise((resolve) =>
    https
      .get(url, function (response) {
        response.pipe(file);
        file.on("finish", function () {
          file.close(resolve()); 
        });
      })
      .on("error", function (err) {
        unlink(dest); // Delete the file async. (But we don't check the result)
      })
  );
}

and call it somewhere after the product is created. where url is the encoded url to the image:

module.exports = async (request, response, deledate, next) => {
  let gallery = get(request, "body.images", []);
  console.log("gallery", gallery);
  const catalogFodler01 = `${Math.floor(Math.random() * (9999 - 1000)) + 1000}`;
  const catalogFodler02 = `${Math.floor(Math.random() * (9999 - 1000)) + 1000}`;

  const targetPath = `catalog/${catalogFodler01}/${catalogFodler02}`;

  if (!existsSync(path.join(CONSTANTS.MEDIAPATH, "catalog"))) {
    mkdirSync(path.join(CONSTANTS.MEDIAPATH, "catalog"));
  }
  if (!existsSync(path.join(CONSTANTS.MEDIAPATH, "catalog", catalogFodler01))) {
    mkdirSync(path.join(CONSTANTS.MEDIAPATH, "catalog", catalogFodler01));
  }
  if (
    !existsSync(
      path.join(
        CONSTANTS.MEDIAPATH,
        "catalog",
        catalogFodler01,
        catalogFodler02
      )
    )
  ) {
    mkdirSync(
      path.join(
        CONSTANTS.MEDIAPATH,
        "catalog",
        catalogFodler01,
        catalogFodler02
      )
    );
  }
  // Download images to local media folder
  return await gallery.map(async (item) => {
    console.log("item", item);
    let url =
      item.indexOf(";") > -1 ? encodeURI(item.split(";")[0]) : encodeURI(item);
    let imageName = item.split("/").pop();
    if(url && url !== undefined){
    await download(url, path.join(CONSTANTS.MEDIAPATH, targetPath, imageName));
    // Wait for product saving to be completed
    const result = await deledate.createProduct;

    const productId = result.insertId;
    const connection = await deledate.getConnection;
    // eslint-disable-next-line no-useless-catch
    try {
      gallery = gallery.filter((image) => {
        let imageName = image.split("/").pop();
        const mediaPath = path.join(CONSTANTS.MEDIAPATH, targetPath, imageName);
        return imageName === image.split("/").pop() && existsSync(mediaPath);
      });

      let mygallery = [];
      gallery.forEach((image) => {
        let imageName = image.split("/").pop();
        mygallery.push(imageName);
      });
      console.log("in SAVEIMAGE mygallery", mygallery, gallery);
      if (mygallery.length > 0) {
        const mainImage = mygallery.shift();
        const mediaPath = path.join(CONSTANTS.MEDIAPATH, targetPath, mainImage);
        const ext = path.extname(
          path.resolve(CONSTANTS.MEDIAPATH, targetPath, mainImage)
        );
        // Generate thumbnail
        if (existsSync(mediaPath)) {
          await sharp(mediaPath)
            .resize(
              config.get("catalog.product.image.thumbnail.width"),
              config.get("catalog.product.image.thumbnail.height"),
              { fit: "inside" }
            )
            .toFile(mediaPath.replace(ext, `-thumb${ext}`));

          // Generate listing
          await sharp(mediaPath)
            .resize(
              config.get("catalog.product.image.listing.width"),
              config.get("catalog.product.image.listing.height"),
              { fit: "inside" }
            )
            .toFile(mediaPath.replace(ext, `-list${ext}`));

          // Generate single
          await sharp(mediaPath)
            .resize(
              config.get("catalog.product.image.single.width"),
              config.get("catalog.product.image.single.height"),
              { fit: "inside" }
            )
            .toFile(mediaPath.replace(ext, `-single${ext}`));
        }

        await update("product")
          .given({ image: `/${targetPath}/${mainImage}`})
          .where("product_id", "=", productId)
          .execute(connection); 
      }

      await Promise.all(
        mygallery.map((f) =>
          (async () => {
            const mediaPath = path.join(CONSTANTS.MEDIAPATH, targetPath, f);
            const ext = path.extname(
              path.resolve(CONSTANTS.MEDIAPATH, targetPath, f)
            );
            if (existsSync(mediaPath)) {
              // Generate thumbnail
              await sharp(mediaPath)
                .resize(
                  config.get("catalog.product.image.thumbnail.width"),
                  config.get("catalog.product.image.thumbnail.height"),
                  { fit: "inside" }
                )
                .toFile(mediaPath.replace(ext, `-thumb${ext}`));

              // Generate listing
              await sharp(mediaPath)
                .resize(
                  config.get("catalog.product.image.listing.width"),
                  config.get("catalog.product.image.listing.height"),
                  { fit: "inside" }
                )
                .toFile(mediaPath.replace(ext, `-list${ext}`));

              // Generate single
              await sharp(mediaPath)
                .resize(
                  config.get("catalog.product.image.single.width"),
                  config.get("catalog.product.image.single.height"),
                  { fit: "inside" }
                )
                .toFile(mediaPath.replace(ext, `-single${ext}`));
            }
            await insert("product_image")
              .given({ image: `/${targetPath}/${f}` })
              .prime("product_image_product_id", productId)
              .execute(connection);
          })()
        )
      );
    } catch (e) {
      // TODO: Log an error here
      throw e;
    }
  }
    next();
  });
};

maybe it helps :)

from evershop.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.