picgo-plugin-s3
Version:
picgo amazon s3 uploader
99 lines (98 loc) • 3.22 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const uploader_1 = __importDefault(require("./uploader"));
const utils_1 = require("./utils");
const config_1 = require("./config");
const pluginName = "aws-s3";
const upload = async (ctx) => {
const userConfig = (0, config_1.loadUserConfig)(ctx);
const client = uploader_1.default.createS3Client(userConfig);
const output = ctx.output;
const tasks = output.map((item, idx) => {
item.uploadDate = new Date();
const fileNameGenerator = new utils_1.FileNameGenerator(item);
return uploader_1.default.createUploadTask({
client,
index: idx,
bucketName: userConfig.bucketName,
path: fileNameGenerator.format(userConfig.uploadPath),
item: item,
acl: userConfig.acl || '',
});
});
let results;
try {
results = await Promise.all(tasks);
}
catch (err) {
ctx.log.error("Upload S3 storage failed, please check your network connection and configuration");
throw err;
}
for (const result of results) {
let { index, url, key, error } = result;
delete output[index].buffer;
delete output[index].base64Image;
output[index].uploadPath = key;
if (error) {
output[index].error = error;
}
else {
output[index].url = url;
output[index].imgUrl = url;
}
}
return ctx;
};
const afterUploadPlugins = (ctx) => {
const userConfig = (0, config_1.loadUserConfig)(ctx);
let errList = [];
ctx.output = ctx.output.reduce((acc, item) => {
if (item.type != pluginName) {
return [...acc, item];
}
if (item.error || (!item.imgUrl && !item.url)) {
errList.push(item);
return acc;
}
const outputURLGenerator = new utils_1.OutputURLGenerator(userConfig, item);
const url = outputURLGenerator.format();
return [...acc, Object.assign(Object.assign({}, item), { imgUrl: url, url: url })];
}, []);
if (errList.length > 0) {
const msg = `S3 Plugin ${errList.length} of ${ctx.output.length + errList.length} failed.`;
for (const item of errList) {
ctx.log.error(`Item ${item.fileName}:`, item.error.message);
}
ctx.emit("notification", {
title: "S3 Plugin Error",
body: msg + " Error list: " + errList.map(item => item.fileName).join(", "),
});
if (ctx.output.length > 0) {
ctx.log.error(msg);
}
else {
throw new Error(msg);
}
}
};
const config = (ctx) => {
return (0, config_1.getPluginConfig)(ctx);
};
module.exports = (ctx) => {
const register = () => {
ctx.helper.uploader.register(pluginName, {
handle: upload,
config,
name: "Amazon S3",
});
ctx.helper.afterUploadPlugins.register(pluginName, {
handle: afterUploadPlugins,
config,
});
};
return {
register,
};
};