javascript - 使用 s3 和 multer 上传单元测试文件
问题描述
我有一个带有此路由POST api/questions/media的Express应用程序,它从客户端 req获取FormData文件(在我的情况下这是一个图像)并将它们保存到AWS S3中。在将图像存储到S3之前,我使用multerS3Transform 和sharp转换图像。如何编写一些测试来模拟multerS3Transfor和S3?
import aws from 'aws-sdk'
import multer from 'multer'
import multerS3Transform from 'multer-s3-transform'
import sharp from 'sharp'
router.post(
'api/questions/media',
() => {
uploadsQuestionImgs(req, res, error => {
if (error) {
return res.status(400).json({
message: `Invalid request. ${error}`,
})
} else {
// If File not found
if (req.files === undefined) {
logger.error('Error: No File Selected!')
return res.status(406).json('Error: No File Selected')
} else {
// If Success
// do something wit req.files
}
}
})
}
)
const uploadsQuestionImgs = multer({
storage: multerS3Transform({
s3: s3,
bucket: accessBucket,
acl: 'public-read',
shouldTransform: (req, file, cb) => {
// now its transforms img all the time
cb(null, true)
},
transforms: [
{
id: 'img',
key: (req, file, cb) => {
const pathName = parseMetaData(file.originalname, req.user)
cb(null, pathName)
},
transform: (req, file, cb) => {
cb(
null,
sharp()
.resize(800, 600)
.jpeg()
)
},
},
],
key: function(req, file, cb) {
const pathName = parseMetaData(file.originalname, req.user)
cb(
null,
path.basename(pathName, path.extname(pathName)) +
'-' +
Date.now() +
path.extname(pathName)
)
},
}),
limits: { fileSize: 2000000 }, // In bytes: 2000000 bytes = 2 MB
fileFilter: function(req, file, cb) {
checkFileType(file, cb)
},
}).array('files', 50)
解决方案
推荐阅读
- javascript - 当我调用一个 api 时,我可以解决这个问题,它用 reactjs 调用了两次吗?
- c - 如何通过 esp32 ap 模式连接互联网
- c# - 在 C# 中将 Base64 内容嵌入到 HTML 中
- java - 从 maven-jaxb2-plugin 0.14.0 迁移到 jaxb2-maven-plugin 2.5.0
- javascript - React 钩子真的必须从“使用”开始吗?
- sql - 根据其他表中的列更新列
- python - 如何在python中获取文件夹的文件描述符
- java - 默认情况下不应该设置构造函数吗?
- pandas - 为什么要在 PySpark 中导入熊猫?
- r - 在森林图中将特定行的字体更改为粗体