javascript - 如何使 AWS S3 上传可重用函数并在我选择的任何文件中使用来自 AWS 的回调?
问题描述
考虑以下 S3 上传代码:
const Category = require('../models/category');
const Link = require('../models/link');
const slugify = require('slugify');
const uuidv4 = require('uuid/v4');
const AWS = require('aws-sdk');
// s3
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION,
});
// Using BASE 64
exports.create = (req, res) => {
const {image, name, content} = req.body;
const base64Data = new Buffer.from(
image.replace(/^data:image\/\w+;base64,/, ''),
'base64'
);
const type = image.split(';')[0].split('/')[1]; // get the png from "data:image/png;base64,"
// upload image to s3 (The params will be passed to the refactored code)
const params = {
Bucket: 'categories-react',
Key: `category/${uuidv4()}.${type}`,
Body: base64Data,
ACL: 'public-read',
ContentEncoding: 'base64',
ContentType: `image/${type}`,
};
s3.upload(params, (err, data) => {
if (err) {
console.log(err);
res.status(400).json({error: 'Upload to s3 failed'});
}
// ... more logic
return res.json(success : '....');
});
};
我想将 AWS 上传代码导出到不同的文件并传递参数而不重复相同的代码,重构代码:
/**
* Upload image to S3
*/
const AWS = require('aws-sdk');
const uploadImageToS3 = (params) => {
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION,
});
// ... handle the upload
s3.upload(params, (err, data) => {
if (err) {
console.log(err);
res.status(400).json({error: 'Upload to s3 failed'});
}
// else handle the data ...
});
};
export {uploadImageToS3 as default};
但是如何在任何文件中使用来自 S3的回调函数将使用 S3 的重构代码?
解决方案
您必须接受回调作为此函数的参数。
作为建议,不要使用回调,而是尝试使用 Promise API:
s3.upload(params).promise().then(data => {}).catch(err => {})
您将能够从您的函数中返回一个承诺,并在稍后执行 then/catch。
推荐阅读
- system-verilog - systemverilog - 单个语句中的多个增量运算符如何工作
- vector - Openlayers 4 矢量图
- c# - 如何阻止输入将先前的咨询发送到数据库
- php - Cronjob:在 php 中写入 fwrite
- android - 在锁定屏幕上创建闹钟
- javascript - 无法从 localhost:8081 (expressjs API) 获取数据,我试过 vue-resource 和 axios
- angularjs - 控制器无法识别
- node.js - 从环回登录 API 获取自定义响应
- php - 实时 AJAX 注册问题
- arcgis - 如何在 ArcGis 中使用 gif 符号