Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
2.1 kB
3
Indexable
const { join } = require("path");
const checkFileExists = require("../utils/check-file-exists");
const defaultResponse = require("../utils/default-response-interface");
const { enhancedLocale } = require("../utils/enhanced-locale");

const checkFiles = (...fieldsOptions) => {
  return async (req, res, next) => {
    const locale = req.headers["currentLanguageId"]; // language id to locale messages
    const hostname = req.protocol + "://" + req.headers.host + "/";
    const errors = [];

    for (const field of fieldsOptions) {
      // Check required fields
      if (!field.optional && !field.allowUrl && (!req.files || !req.files[field.name])) {
        errors.push(`${field.name}RequiredError`);
        continue;
      }

      // Process uploaded files
      if (req.files && req.files[field.name]) {
        const fileObjects = Array.isArray(req.files[field.name])
          ? req.files[field.name]
          : [req.files[field.name]];

        if (fileObjects.length > field.maxCount) {
          errors.push(`${field.name}TooManyFilesError`);
          continue;
        }

        const fileUrls = fileObjects.map(fileObject => hostname + fileObject.path);
        req.body[field.name] = fileUrls.length === 1 ? fileUrls[0] : fileUrls;
      }

      // Check URL fields
      if (field.allowUrl) {
        const fieldUrl = req.body[field.name];

        if (!fieldUrl && !req.files[field.name]) {
          errors.push(`${field.name}RequiredError`);
          continue;
        }

        const convertedField = Array.isArray(fieldUrl) ? fieldUrl : [fieldUrl];

        for (const element of convertedField) {
          const filePath = `${element}`.split(hostname);

          if (!filePath[1] || !checkFileExists(join("./", filePath[1]))) {
            errors.push(`${field.name}WrongUrlError`);
          }
        }

        req.body[field.name] = convertedField;
      }
    }

    if (errors.length) {
      const response = await enhancedLocale(locale, errors, defaultResponse({ info: false }));
      return res.status(400).send(response);
    }

    next();
  };
};

module.exports = { checkFiles };