Ghost/core/server/api/canary/email-preview.js
Kevin Ansfield dfca0abc93 Added support for segmented email content in previews and test emails
refs https://github.com/TryGhost/Team/issues/927

- the `email-cta` card can be segmented so only free or paid members can see the content, it should be possible for authors to preview what that will look like in either case
2021-07-27 16:31:41 +01:00

90 lines
3.2 KiB
JavaScript

const models = require('../../models');
const i18n = require('../../../shared/i18n');
const errors = require('@tryghost/errors');
const mega = require('../../services/mega');
const labs = require('../../../shared/labs');
module.exports = {
docName: 'email_preview',
read: {
options: [
'fields',
'memberSegment'
],
validation: {
options: {
fields: ['html', 'plaintext', 'subject']
}
},
data: [
'id',
'status'
],
permissions: true,
query(frame) {
const options = Object.assign(frame.options, {formats: 'html,plaintext', withRelated: ['authors', 'posts_meta']});
const data = Object.assign(frame.data, {status: 'all'});
return models.Post.findOne(data, options)
.then((model) => {
if (!model) {
throw new errors.NotFoundError({
message: i18n.t('errors.api.posts.postNotFound')
});
}
return mega.postEmailSerializer.serialize(model, {isBrowserPreview: true, apiVersion: 'canary'}).then((emailContent) => {
if (labs.isSet('emailCardSegments') && frame.options.memberSegment) {
emailContent = mega.postEmailSerializer.renderEmailForSegment(emailContent, frame.options.memberSegment);
}
const replacements = mega.postEmailSerializer.parseReplacements(emailContent);
replacements.forEach((replacement) => {
emailContent[replacement.format] = emailContent[replacement.format].replace(
replacement.match,
replacement.fallback || ''
);
});
return emailContent;
});
});
}
},
sendTestEmail: {
statusCode: 200,
headers: {},
options: [
'id'
],
validation: {
options: {
id: {
required: true
}
}
},
permissions: true,
async query(frame) {
const options = Object.assign(frame.options, {status: 'all'});
let model = await models.Post.findOne(options, {withRelated: ['authors']});
if (!model) {
throw new errors.NotFoundError({
message: i18n.t('errors.api.posts.postNotFound')
});
}
const {emails = [], memberSegment} = frame.data;
const response = await mega.mega.sendTestEmail(model, emails, 'canary', memberSegment);
if (response && response[0] && response[0].error) {
throw new errors.EmailError({
statusCode: response[0].error.statusCode,
message: response[0].error.message,
context: response[0].error.originalMessage
});
}
return response;
}
}
};