-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
239 lines (230 loc) · 6.69 KB
/
index.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
var _ = require('lodash');
module.exports = {
extend: 'apostrophe-pieces',
name: 'apostrophe-redirect',
alias: 'redirects',
label: 'Redirect',
pluralLabel: 'Redirects',
searchable: false,
adminOnly: true,
// Default type being joined for internal redirects.
// Can be overwritten project level with an array of
// multiple piece types: ex: [ 'apostrophe-page', 'news', 'people' ]
withType: 'apostrophe-page',
// Default status code. Must be one of the valid choices
// for the `statusCode` select field
statusCode: 302,
openGraph: false, // Disables apostrophe-open-graph for redirects
seo: false, // Disables apostrophe-seo for redirects
sitemap: false, // Disables apostrophe-site-map for redirects
addFields: [
{
name: 'redirectSlug',
// This is *not* type: 'slug' because we want to let you match any
// goldang nonsense the old site had in there, including mixed case
type: 'string',
label: 'Old URL',
help: 'Format with leading / such as /old-url',
required: true
},
{
// contextual flag set so you don't see it in the editor; this gets updated
// by beforeSave
type: 'slug',
name: 'slug',
label: 'Slug',
required: true,
contextual: true
},
{
name: 'title',
label: 'Description',
type: 'string',
required: true
},
{
// contextual: true to hide this property
type: 'boolean',
name: 'published',
label: 'Published',
required: true,
def: true,
contextual: true
},
{
name: 'urlType',
label: 'Link To',
type: 'select',
choices: [
{ label: 'Internal Page', value: 'internal', showFields: [ '_newPage' ] },
{ label: 'External URL', value: 'external', showFields: [ 'externalUrl' ] }
]
},
{
name: 'ignoreQueryString',
label: 'Ignore query string when matching.',
type: 'boolean',
def: false
},
{
name: '_newPage',
type: 'joinByOne',
withType: 'apostrophe-page',
label: 'Page Title',
idField: 'pageId',
filters: {
projection: { slug: 1, title: 1, _url: 1 },
// Admins set up redirects, so it's OK for non-admins to follow them anywhere
// (they won't actually get access without logging in)
permission: false
}
},
{
name: 'externalUrl',
label: 'URL',
type: 'url'
},
{
name: 'statusCode',
label: 'Redirect Type',
type: 'select',
help: 'Test new redirects as temporary redirects first. Permanent redirects are an SEO best practice, but only if they are correct.',
choices: [
{ label: 'Temporary', value: '302' },
{ label: 'Permanent', value: '301' }
],
def: '302'
}
],
removeFields: ['tags'],
arrangeFields: [
{
name: 'info',
label: 'Info',
fields: [
'redirectSlug',
'title',
'urlType',
'ignoreQueryString',
'_newPage',
'externalUrl',
'statusCode'
]
}
],
beforeConstruct: function (self, options) {
var _newPage = _.find(options.addFields, { name: '_newPage' });
_newPage.withType = options.withType;
var field = _.find(options.addFields, { name: 'statusCode' });
if (!field) {
return;
}
field.def = options.statusCode.toString();
if (field.def === '301') {
field.help = 'By default, redirects are permanent and Google will cache them. Please proofread this carefully or test first with the "temporary" setting.';
}
},
construct: function (self, options) {
self.beforeSave = function (req, doc, options, callback) {
// prefix the actual slug so it's not treated as a page
doc.slug = 'redirect-' + doc.redirectSlug;
if (!doc.title) {
doc.title = doc.redirectSlug;
}
return callback(null);
};
// Check to see if a redirect exists before sending user on their way
self.expressMiddleware = async (req, res, next) => {
let slug = req.url;
let pathOnly = slug.split('?')[0];
let redirectRegEx = new RegExp(`^redirect-${self.apos.utils.regExpQuote(pathOnly)}(\\?.*)?$`);
const workflow = self.apos.modules['apostrophe-workflow'];
const locales = workflow && Object.keys(workflow.locales).filter(locale => !locale.endsWith('-draft'));
const $or = locales && [
{
workflowLocale: {
$in: locales
}
},
{
workflowLocale: {
$exists: 0
}
}
];
try {
const criteria = {
slug: redirectRegEx,
type: self.name,
trash: {
$ne: true
},
published: true
};
if ($or) {
criteria.$or = $or;
}
const results = await self.apos.docs.db.find(criteria).project({
title: 1,
slug: 1,
urlType: 1,
ignoreQueryString: 1,
pageId: 1,
type: 1,
externalUrl: 1,
redirectSlug: 1,
statusCode: 1,
_newPage: 1,
workflowLocale: 1
}).toArray();
const target = results &&
results.find(result => result.redirectSlug === slug) ||
results.find(result => result.redirectSlug === pathOnly && result.ignoreQueryString);
if (!target) {
return next();
}
let status = parseInt(target.statusCode);
if (isNaN(status) || !status) {
status = 302;
}
if (target.urlType === 'internal') {
const criteria = {
_id: target.pageId,
trash: {
$ne: true
},
published: true
};
if ($or) {
criteria.$or = $or;
}
const doc = await self.apos.docs.db.findOne(criteria);
if (doc) {
const manager = self.apos.docs.getManager(doc.type);
if (!manager) {
return next();
}
let oldLocale;
try {
oldLocale = req.locale;
req.locale = doc.workflowLocale;
target._newPage = await manager.find(req, { _id: target.pageId }).toObject();
} finally {
req.locale = oldLocale;
}
}
if (!target._newPage) {
return next();
}
return req.res.redirect(status, target._newPage._url);
} else if (target.urlType === 'external' && target.externalUrl.length) {
return req.res.redirect(status, target.externalUrl);
}
return next();
} catch (e) {
self.apos.utils.error(e);
return next();
}
};
}
};