0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-02-03 23:00:14 -05:00
ghost/core/server/api/canary/email-previews.js
Kevin Ansfield 27337e5f00
Added newsletter param to email preview endpoint (#14820)
refs https://github.com/TryGhost/Team/issues/1621

We want to allow previewing emails based on the selected newsletter. The post model doesn't get a newsletter attached until a publish occurs so we can't use `post.newsletter` and need to give the option of specifying which newsletter to preview via query params.

- added support for `newsletter` query param on the `GET /email_previews/posts/:id/` endpoint where the value is a newsletter slug
- updated `generateEmailContent()` signature to use an options object because the order of memberSegment/newsletter arguments doesn't matter and is difficult to reason about if not named
- adjusted `generateEmailContent()` to fetch the newsletter matching the provided slug, falling back to the default newsletter if no slug is provided
2022-05-16 12:15:54 +01:00

77 lines
2.1 KiB
JavaScript

const models = require('../../models');
const tpl = require('@tryghost/tpl');
const errors = require('@tryghost/errors');
const mega = require('../../services/mega');
const messages = {
postNotFound: 'Post not found.'
};
const emailPreview = new mega.EmailPreview();
module.exports = {
docName: 'email_previews',
read: {
options: [
'fields',
'memberSegment',
'newsletter'
],
validation: {
options: {
fields: ['html', 'plaintext', 'subject']
}
},
data: [
'id',
'status'
],
permissions: true,
async query(frame) {
const options = Object.assign(frame.options, {formats: 'html,plaintext', withRelated: ['authors', 'posts_meta']});
const data = Object.assign(frame.data, {status: 'all'});
const model = await models.Post.findOne(data, options);
if (!model) {
throw new errors.NotFoundError({
message: tpl(messages.postNotFound)
});
}
return emailPreview.generateEmailContent(model, {
newsletter: frame.options.newsletter,
memberSegment: frame.options.memberSegment
});
}
},
sendTestEmail: {
statusCode: 204,
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: tpl(messages.postNotFound)
});
}
const {emails = [], memberSegment} = frame.data;
return await mega.mega.sendTestEmail(model, emails, memberSegment);
}
}
};