Как загрузить файлы S3 в KeystoneJS

У меня есть элемент с именем style, который имеет 2 атрибута: один с необработанным текстом css, а другой с S3Файл.

Style.add({
  ...
  css: { type: Types.Code, language: 'css' },
  cssFile: {
    type: Types.S3File,
    s3path: 'uploads/assets',
  },
  ...
});

Я хочу обновить S3File, указав содержимое текста css.

function uploadCSStoAmazon(style) {
  // Store css code in temporal file (with a md5 name)
  var rndm = crypto.randomBytes(20).toString('hex'), file_path = '/tmp/css_temp_' + rndm + '.css';

  fs.writeFile(file_path, style.css, function(err) {
    if(err) {
      return console.log(err);
    }

    console.log("The file was saved!");

    // style.cssFile = new Types.S3File();

    // TODO upload file to amazon
    style.cssFile._.uploadFile(file_path, true, function(err, fileData){
      // TODO erase css file
    });
  });

}

...

var aStyle = new Style.model({
  ...
  css: 'Some css string',
  ...
});


...

uploadCSStoAmazon(aStyle);

Атрибут cssFile не определен, я так понимаю, но как мне создать новый файл и присвоить его этому атрибуту, а также загрузить файл?


person dvdcastro    schedule 28.05.2015    source источник
comment
Как/куда вы звоните uploadCSStoAmazon()?   -  person JME    schedule 29.05.2015
comment
Я только что отредактировал вопрос, чтобы показать, как я буду вызывать функцию.   -  person dvdcastro    schedule 29.05.2015


Ответы (1)


Я узнал, как вы можете использовать updateHandler, который поставляется с Keystone. Однако они все еще используют форму req.files express 3.x.

// A express file generator

function writeToFile(fileName, txt, ext, callback) {
  var rndm = crypto.randomBytes(20).toString('hex'), file_path = '/tmp/css_temp_' + rndm + '.' + ext, the_file = {};

  fs.writeFile(file_path, txt, function(err) {
    if(err) {
      callback(null, err);
    }

    var stats = fs.statSync(file_path);
    var fileSizeInBytes = stats["size"];

    the_file.path = file_path;
    the_file.name = fileName + '.' + ext;
    the_file.type = 'text/' + ext;
    the_file.size = fileSizeInBytes;

    console.log("The file was cached!");
    callback(the_file, err);
  });
}

...

/**
 * Update Style by ID
 */
exports.update = function(req, res) {
  var data = (req.method == 'POST') ? req.body : req.query;

  Style.model.findById(data._id).exec(function(err, item) {
    
    if (err) return res.apiError('database error', err);
    if (!item) return res.apiError('not found');

    writeToFile(item.slug, data.css, 'css', function(req_file, err){

      if (err) return res.apiError('update error during file cache', err);

      req.files['cssFile_upload'] = req_file;

      item.getUpdateHandler(req).process(data, function(err) {
      
        if (err) return res.apiError('update error', err);

        res.apiResponse({
          success: true
        });

      }); // end process

    }); // end writeToFile

  });
};

person dvdcastro    schedule 31.05.2015