This repository has been archived by the owner on Dec 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (61 loc) · 1.84 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
'use strict';
const validChangeFreq = [
'always',
'hourly',
'daily',
'weekly',
'monthly',
'yearly',
'never'
];
const sitemap = options => {
const sitemapUrl = options && options.sitemapUrl ? options.sitemapUrl : '/sitemap.xml';
const urls = options && options.urls ? options.urls : [];
return (req, res, next) => {
if (req.url === sitemapUrl) {
res.header('Content-Type', 'application/xml');
let xmlUrls = '';
urls.forEach(url => {
if (!('url' in url) || !url.url) {
return;
}
const lineUrl = `<loc>${url.url}</loc>`;
const lineLastMod = 'lastmod' in url ? `<lastmod>${url.lastmod}</lastmod>` : '';
const lineChangeFreq = 'changefreq' in url && validChangeFreq.indexOf(url.changefreq) !== -1 ? `<changefreq>${url.changefreq}</changefreq>` : '';
const linePriority = 'priority' in url && url.priority >= 0 && url.priority <= 1 ? `<priority>${url.priority}</priority>` : '';
xmlUrls += getUrl(lineUrl, lineLastMod, lineChangeFreq, linePriority);
});
res.send(getXml(xmlUrls));
}
next();
};
};
const getUrl = (url, lastMod, changeFreq, priority) => {
let result = `
<url>
${url}`;
if (lastMod) {
result += `
${lastMod}`;
}
if (changeFreq) {
result += `
${changeFreq}`;
}
if (priority) {
result += `
${priority}`;
}
result += `
</url>`;
return result;
};
const getXml = urls => {
return `
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">${urls}
</urlset>
`.trim();
};
module.exports = sitemap;
module.exports.default = module.exports;