I have changed multer to multer-s3. Changing in controllers for that. I will store "location" instead of "filename". But I am getting typescript error.
I am using Localstack for now.
Here is my code:
multer.s3.middleware.ts
import validateFileForBucket from '@/common/validateFileForBucket';
import { AWS_BUCKET_NAME } from '@/config';
import aws from 'aws-sdk';
import multer from 'multer';
import multerS3 from 'multer-s3';
// Configure AWS for localstack
aws.config.update({
accessKeyId: 'testKEYId',
secretAccessKey: 'testSecret',
region: 'ap-south-1',
sslEnabled: false,
endpoint: 'http://localhost:4566',
s3ForcePathStyle: true,
} as any);
const s3 = new aws.S3();
// Define Multer-S3 upload
const uploadS3 = multer({
fileFilter: (req, file, cb) => {
const bucket = req.params.bucket;
validateFileForBucket(bucket, file, cb);
},
storage: multerS3({
s3: s3 as any,
bucket: AWS_BUCKET_NAME as string,
metadata: function (req, file, cb) {
cb(null, { fieldName: file.fieldname });
},
key: function (req: any, file, cb) {
const bucket = req.params.bucket ? `${req.params.bucket}/` : '';
cb(null, `${bucket}${Date.now()}-${file.originalname}`);
},
}),
});
export default uploadS3;
user.route.ts
this.router
.route('/create')
.post(
authMiddleware,
uploadS3.single('profileImage'),
validationMiddleware(createUserSchema, 'body'),
this.userController.create,
);
user.controller.ts
public create = async (req: Request, res: Response) => {
req.body.profileImage = req.file?.location;
req.body.user = req.tokenData.user;
const responseData = await this.userRepository.createUser(req.body as CreateUserInterface);
return generalResponse(req, res, responseData, successMessage.USER_CREATE_SUCCESS, false, responseFlag.SUCCESS);
};
For some reason, I am getting typescript error:
TSError: тип Unable to compile TypeScript:
src/controllers/user/user.controller.ts:24:39 - error TS2339: Property 'location' does not exist on type 'File'.
24 req.body.profileImage = req.file?.location;
I get file data if I log req.file, and it has location on it.
req.file: {
fieldname: 'profileImage',
originalname: 'profile.jpeg',
encoding: '7bit',
mimetype: 'image/jpeg',
size: 6182,
bucket: 'aws-bucket-name',
key: '1711716164482-profile.jpeg',
acl: 'private',
contentType: 'application/octet-stream',
contentDisposition: null,
contentEncoding: null,
storageClass: 'STANDARD',
serverSideEncryption: null,
metadata: { fieldName: 'profileImage' },
location: 'http://localhost:4566/aws-bucket-name/1711716164482-profile.jpeg',
etag: '"806170f0b2a191c8c967372af939cc6d"',
versionId: undefined
}
Hovering over req.file shows
(property) Express.Request.file?: Express.Multer.File | undefined
Multer.File object populated by single() middleware.
Shouldn't it be Express.MulterS3.File?
being TS newbie, I have no idea how to fix this. I have searched on google, stackoverflow and also on multer-s3 github issues. But no one seems to have got similar error.
I am not sure What I am doing wrong. Thank you in advance.