payload-s3-upload
Version:
Send Payload CMS uploads to Amazon S3
77 lines • 3.5 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const client_s3_1 = require("@aws-sdk/client-s3");
const getFilesToUpload = ({ data, req, }) => {
var _a, _b, _c, _d;
const reqFile = (_c = (_b = (_a = req.files) === null || _a === void 0 ? void 0 : _a.file) !== null && _b !== void 0 ? _b : req.file) !== null && _c !== void 0 ? _c : null;
if (reqFile == null)
return [];
const files = [
{
filename: data.filename,
mimeType: data.mimeType,
buffer: reqFile.data,
},
];
if (((_d = data.mimeType) === null || _d === void 0 ? void 0 : _d.includes('image')) && data.sizes != null) {
Object.entries(data.sizes).forEach(([key, sizeData]) => {
const buffer = req.payloadUploadSizes[key];
const { filename } = sizeData;
if (buffer != null || filename != null) {
files.push({
buffer,
filename,
mimeType: data.mimeType,
});
}
});
}
return files;
};
const buildUploadHook = (s3Client, collection) => {
const { s3 } = collection.upload;
const uploadHook = (beforeChangeOptions) => __awaiter(void 0, void 0, void 0, function* () {
const files = getFilesToUpload(beforeChangeOptions);
for (const file of files) {
let key = file.filename;
if (s3.prefix) {
key =
s3.prefix instanceof Function
? path_1.default.posix.join(s3.prefix({ doc: beforeChangeOptions.data }), key)
: path_1.default.posix.join(s3.prefix, key);
}
let putObjectCommandInput = {
Bucket: s3.bucket,
Key: key,
Body: file.buffer,
};
if (file.mimeType) {
putObjectCommandInput.ContentType = file.mimeType;
}
if (s3.commandInput) {
const commandInputEntries = Object.entries(s3.commandInput).map(([property, value]) => [
property,
typeof value === 'function' ? value(beforeChangeOptions) : value,
]);
putObjectCommandInput = Object.assign(Object.assign({}, putObjectCommandInput), Object.fromEntries(commandInputEntries));
}
yield s3Client.send(new client_s3_1.PutObjectCommand(putObjectCommandInput));
}
});
return uploadHook;
};
exports.default = buildUploadHook;
//# sourceMappingURL=buildUploadHook.js.map