Возможность загрузки файлов с помощью Sails.js - PullRequest
0 голосов
/ 18 апреля 2019

Возможно ли, чтобы действие Sails принимало необязательную загрузку файла без , выплевывая следующую трассировку стека через несколько секунд после запроса?

Upstream (file upload: `image`) emitted an error: { Error: EMAXBUFFER: An upstream (`NOOP_image`) timed out before it was plugged into a receiver. It was still unused after waiting 4500ms. You can configure this timeout by changing the `maxTimeToBuffer` option.

Note that this error might be occurring due to an earlier file upload that is finally timing out after an unrelated server error.
    at Timeout.<anonymous> (/home/jarrod/workspace/cuckold/Cuckold-API/node_modules/skipper/lib/private/Upstream/Upstream.js:86:15)
    at ontimeout (timers.js:498:11)
    at tryOnTimeout (timers.js:323:5)
    at Timer.listOnTimeout (timers.js:290:5)
  code: 'EMAXBUFFER',
  message: 'EMAXBUFFER: An upstream (`NOOP_image`) timed out before it was plugged into a receiver. It was still unused after waiting 4500ms. You can configure this timeout by changing the `maxTimeToBuffer` option.\n\nNote that this error might be occurring due to an earlier file upload that is finally timing out after an unrelated server error.' }

Для полноты я использую специальный адаптер Skipper для выгрузки файлов в minio , который я свободно использовал в адаптере skipper-s3 , но я также вижу те же симптомы, используя хранилище по умолчаниюАдаптер files-in-.tmp-directory.

Приведенный ниже код работает правильно, принимает и сохраняет одну загрузку файла, если она указана в HTTP-запросе, но если поле image опущено, выводится приведенное выше.на консоль ~ через 4,5 секунды после указанного запроса.

Ниже приведены наиболее интересные части рассматриваемого действия:

module.exports = {
  friendlyName: 'Create or update a news article',

  files: ['image'],

  inputs: {
    id: {
      type: 'number',
      description: 'ID of article to edit (omit for new articles)'
    },

    content: {
      type: 'string',
      description: 'Markdown-formatted content of news artcle',
      required: true
    },

    image: {
      type: 'ref'
    },
  },

  exits: {
    success: { }
  },

  fn: async function (inputs, exits) {
    let id = inputs.id;
    let article;

    console.log('About to grab upload(s)')
    let uploadedFiles = await (new Promise((resolve, reject) => {
      this.req.file('image').upload({/* ... */}, (err, uploadedFiles) => {
        console.log('Upload stuff callback', [err, uploadedFiles])
        if (err) {
          sails.log.error(`Unable to store uploads for news article`, err.stack)
          return reject(new Error('Unable to store uploads')); // Return a vague message to the client
        }
        resolve(uploadedFiles)
      });
    }));

    console.log('uploadedFiles', uploadedFiles)
    if (uploadedFiles && uploadedFiles.length) {
      uploadedFiles = uploadedFiles.map(f => f.fd)
    } else {
      uploadedFiles = null
    }

    // Do some database updating

    return exits.success({ article });
  }
};

Если в запросе HTTP не было загрузки, тогда uploadedFiles являетсяпустой массив и остальная часть кода действия выполняются без проблем, но я не хочу, чтобы журналы были полны такого рода бесполезных действий.

1 Ответ

0 голосов
/ 18 апреля 2019

Оказывается, на самом деле все просто, просто извлеките модуль sails-hook-uploads из npm и замените завернутый в Promise обломок в первоначальном вопросе чем-то вроде этого

let uploadedFiles = await sails.upload(inputs.image, {/* custom adapter config */});

Похоже, что работает должным образом, но не регистрирует предупреждение о том, что загрузка не была перехвачена во времени, если в запросе ничего не указано.

Приведено к этому решению приложением Пример Ration, здесь .

...