-
-
Notifications
You must be signed in to change notification settings - Fork 10.1k
/
post-email-serializer.js
80 lines (72 loc) · 2.72 KB
/
post-email-serializer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const juice = require('juice');
const template = require('./template');
const settingsCache = require('../../services/settings/cache');
const urlUtils = require('../../lib/url-utils');
const moment = require('moment');
const cheerio = require('cheerio');
const api = require('../../api');
const getSite = () => {
return Object.assign({}, settingsCache.getPublic(), {
url: urlUtils.urlFor('home', true)
});
};
/**
* createUnsubscribeUrl
*
* Takes a member and returns the url that should be used to unsubscribe
* In case of no member, generates the preview unsubscribe url - `?preview=1`
*
* @param {object} member
* @param {string} member.uuid
*/
const createUnsubscribeUrl = (member) => {
const siteUrl = urlUtils.getSiteUrl();
const unsubscribeUrl = new URL(siteUrl);
unsubscribeUrl.pathname = `${unsubscribeUrl.pathname}/unsubscribe/`.replace('//', '/');
if (member.uuid) {
unsubscribeUrl.searchParams.set('uuid', member.uuid);
} else {
unsubscribeUrl.searchParams.set('preview', '1');
}
return unsubscribeUrl.href;
};
// NOTE: serialization is needed to make sure we are using current API and do post transformations
// such as image URL transformation from relative to absolute
const serializePostModel = async (model) => {
const frame = {options: {context: {user: true}}};
const apiVersion = model.get('api_version') || 'v3';
const docName = 'posts';
await api.shared
.serializers
.handle
.output(model, {docName: docName, method: 'read'}, api[apiVersion].serializers.output, frame);
return frame.response[docName][0];
};
const serialize = async (postModel, options = {isBrowserPreview: false}) => {
const post = await serializePostModel(postModel);
post.published_at = post.published_at ? moment(post.published_at).format('DD MMM YYYY') : moment().format('DD MMM YYYY');
post.authors = post.authors && post.authors.map(author => author.name).join(',');
post.html = post.html || '';
if (post.posts_meta) {
post.email_subject = post.posts_meta.email_subject;
}
let htmlTemplate = template({post, site: getSite()});
if (options.isBrowserPreview) {
const previewUnsubscribeUrl = createUnsubscribeUrl({});
htmlTemplate = htmlTemplate.replace('%recipient.unsubscribe_url%', previewUnsubscribeUrl);
}
let juicedHtml = juice(htmlTemplate);
// Force all links to open in new tab
let _cheerio = cheerio.load(juicedHtml);
_cheerio('a').attr('target','_blank');
juicedHtml = _cheerio.html();
return {
subject: post.email_subject || post.title,
html: juicedHtml,
plaintext: post.plaintext
};
};
module.exports = {
serialize,
createUnsubscribeUrl
};