@chevre/domain
Version:
Chevre Domain Library for Node.js
137 lines (136 loc) • 6.6 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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendEmailMessage = sendEmailMessage;
const client_1 = require("@sendgrid/client");
// import * as sgMail from '@sendgrid/mail';
const http_status_1 = require("http-status");
const util = require("util");
const factory = require("../../factory");
const factory_1 = require("./factory");
function createSendEmailMessageActionAttributes(params) {
var _a;
const { agent, object, project, purpose, recipient, typeOf } = params;
return Object.assign({ agent, object, project, purpose, recipient, typeOf }, (typeof ((_a = params.sameAs) === null || _a === void 0 ? void 0 : _a.id) === 'string') ? { sameAs: { id: params.sameAs.id, typeOf: 'Task' } } : undefined);
}
function createMailData(params) {
return (repos, credentials) => __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c, _d;
const project = yield repos.project.findById({
id: params.project.id,
inclusion: ['settings']
});
let mailData;
let apiKey = credentials.sendGrid.apiKey;
// プロジェクト固有のSendGrid設定があれば、そちらを使用
if (typeof ((_a = project.settings) === null || _a === void 0 ? void 0 : _a.sendgridApiKey) === 'string' && project.settings.sendgridApiKey.length > 0) {
apiKey = project.settings.sendgridApiKey;
}
if (typeof apiKey !== 'string') {
throw new factory.errors.Internal('API Key not found');
}
// sgMail.setApiKey(apiKey); // fix(2025-03-14~)
let emailMessage;
if (typeof params.object.text === 'string') {
emailMessage = params.object;
}
else {
// メッセージリポジトリに対応(2024-04-29~)
emailMessage = yield repos.message.findByIdentifier({
identifier: params.object.identifier,
project: { id: project.id }
});
}
const emailMessageFrom = {
name: emailMessage.sender.name,
email: emailMessage.sender.email
};
// プロジェクト設定対応(2023-08-21~)
const senderEmailByProjectSettings = (_d = (_c = (_b = project.settings) === null || _b === void 0 ? void 0 : _b.sendEmailMessage) === null || _c === void 0 ? void 0 : _c.sender) === null || _d === void 0 ? void 0 : _d.email;
if (typeof senderEmailByProjectSettings === 'string' && senderEmailByProjectSettings.length > 0) {
emailMessageFrom.email = senderEmailByProjectSettings;
}
const subject = emailMessage.about.name;
const emailDatas = (Array.isArray(emailMessage.toRecipient))
? emailMessage.toRecipient.map((toRecipient) => {
return {
name: toRecipient.name,
email: toRecipient.email
};
})
: [];
mailData = Object.assign({ to: emailDatas, from: emailMessageFrom, subject }, (String(emailMessage.text).length > 0) ? { text: String(emailMessage.text) } : undefined);
return { mailData, emailMessage, apiKey };
});
}
/**
* https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html
*/
function sendEmailMessage(params) {
return (repos, credentials) => __awaiter(this, void 0, void 0, function* () {
const { mailData, emailMessage, apiKey } = yield createMailData(params)(repos, credentials);
// add recipe(2025-03-12~)
let recipe = (0, factory_1.createSendEmailMessageRecipe)({
mailData,
project: { id: params.project.id }
});
const startingAction = createSendEmailMessageActionAttributes(params);
const action = yield repos.action.start(startingAction, { recipe });
let result = {};
try {
mailData.customArgs = {
emailMessage: emailMessage.identifier,
actionId: action.id, // 追跡用に通知IDをカスタムフィールドとしてセットする
projectId: params.project.id
};
// reimplement using Client(2025-03-14~)
// const response = await sgMail.sendMultiple(mailData);
const sgClient = new client_1.Client();
sgClient.setApiKey(apiKey);
const response = yield sgClient.request({
body: {
content: [{ type: 'text/plain', value: mailData.text }],
from: mailData.from,
personalizations: [{ to: mailData.to }],
subject: mailData.subject,
custom_args: mailData.customArgs
},
method: 'POST',
url: '/v3/mail/send'
});
// check the response.
if (response[0].statusCode !== http_status_1.ACCEPTED) {
throw new factory.errors.Internal(`sendgrid request not accepted. response is ${util.inspect(response)}`);
}
const { statusCode } = response[0];
result = { statusCode };
recipe = (0, factory_1.createSendEmailMessageRecipe)({
mailData,
afterMedia: result,
project: { id: params.project.id }
});
}
catch (error) {
try {
recipe = (0, factory_1.createSendEmailMessageRecipe)({
mailData,
project: { id: params.project.id }
});
yield repos.action.giveUp({ typeOf: action.typeOf, id: action.id, error, recipe });
}
catch (__) {
// 失敗したら仕方ない
}
throw error;
}
yield repos.action.completeWithVoid({ typeOf: action.typeOf, id: action.id, result: result, recipe });
});
}
;