dimanche 20 février 2022

How to design a complex function for scalability?

I have an app that needs to process various types of user uploaded files. The most common is images.

However not all images are handled in the same way. How they are processed depends on what they'll be used for e.g. a product image needs to be much bigger size than a profile picture.

I have made a single function called processImage() which takes in arguments about the image that needs processing and creates different size images etc.

Its layout is like this:

mediahandler.js

processImage({ area, usage, uploadto, filepath, mimetype, etc, etc });
{
  // This could be a number of places like S3, Google Drive

  if (area === "Shop") {
    // What area will this image be used in? Determines properties and metadata of images

    if (usage === "Hero") {
      // What is the purpose of the image?
      // Hero images will be large and high quality

      if (uploadto === "SSD") {
        // Now write to serveer hard drive using file system
      } else if (uploadto === "S3") {
        // Now upload to S3 using a buffer
      }
    } else if (usage === "Thumbnail") {
      // Thumbnails will be small and low quality
      if (uploadto === "SSD") {
        // Now write to serveer hard drive using file system
      } else if (uploadto === "S3") {
        // Now upload to S3 using a buffer
      }
    }
  }
}
// Other functions
 processVideo(){ }

As you can see the number of if/else or even switch statements grows quickly. I fear this will be end up becoming a huge convoluted do-it-all function which may not scale well (I really don't know if this is even a legitimate concern).

If I was to break this function apart and create several functions e.g. processStoreImage() and processPofileImage() then I will end up repeating a lot of code between them and violate the DRY (Don’t Repeat Yourself) principle.

Is there a 'better' way of going about this?

Aucun commentaire:

Enregistrer un commentaire