Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support Many to Many relationships #139

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ end_of_line = LF
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
quote_type = single

[*.md]
trim_trailing_whitespace = false
4 changes: 4 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"trailingComma": "all",
"arrowParens": "always"
}
4 changes: 3 additions & 1 deletion server/controllers/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ module.exports = {

updateSettings: async (ctx) => {
const config = await getService('settings').getConfig();
const newContentTypes = Object.keys(ctx.request.body.contentTypes).filter((x) => !Object.keys(config.contentTypes).includes(x));
const newContentTypes = Object.keys(ctx.request.body.contentTypes).filter(
(x) => !Object.keys(config.contentTypes).includes(x),
);

await strapi
.store({
Expand Down
262 changes: 164 additions & 98 deletions server/services/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
*/

const { getConfigUrls } = require('@strapi/utils');
const { SitemapStream, streamToPromise, SitemapAndIndexStream } = require('sitemap');
const {
SitemapStream,
streamToPromise,
SitemapAndIndexStream,
} = require('sitemap');
const { isEmpty } = require('lodash');

const { logMessage, getService, formatCache, mergeCache } = require('../utils');
Expand All @@ -26,31 +30,39 @@ const getLanguageLinks = async (config, page, contentType, defaultURL) => {
const links = [];
links.push({ lang: page.locale, url: defaultURL });

await Promise.all(page.localizations.map(async (translation) => {
let { locale } = translation;

// Return when there is no pattern for the page.
if (
!config.contentTypes[contentType]['languages'][locale]
&& config.contentTypes[contentType]['languages']['und']
) {
locale = 'und';
} else if (
!config.contentTypes[contentType]['languages'][locale]
&& !config.contentTypes[contentType]['languages']['und']
) {
return null;
}
await Promise.all(
page.localizations.map(async (translation) => {
let { locale } = translation;

// Return when there is no pattern for the page.
if (
!config.contentTypes[contentType]['languages'][locale] &&
config.contentTypes[contentType]['languages']['und']
) {
locale = 'und';
} else if (
!config.contentTypes[contentType]['languages'][locale] &&
!config.contentTypes[contentType]['languages']['und']
) {
return null;
}

const { pattern } = config.contentTypes[contentType]['languages'][locale];
const translationUrl = await strapi.plugins.sitemap.services.pattern.resolvePattern(pattern, translation);
let hostnameOverride = config.hostname_overrides[translation.locale] || '';
hostnameOverride = hostnameOverride.replace(/\/+$/, '');
links.push({
lang: translation.locale,
url: `${hostnameOverride}${translationUrl}`,
});
}));
const { pattern } = config.contentTypes[contentType]['languages'][locale];

const translationUrl =
await strapi.plugins.sitemap.services.pattern.resolvePattern(
pattern,
translation,
);
let hostnameOverride =
config.hostname_overrides[translation.locale] || '';
hostnameOverride = hostnameOverride.replace(/\/+$/, '');
links.push({
lang: translation.locale,
url: `${hostnameOverride}${translationUrl}`,
});
}),
);

return links;
};
Expand All @@ -70,19 +82,23 @@ const getSitemapPageData = async (config, page, contentType) => {

// Return when there is no pattern for the page.
if (
!config.contentTypes[contentType]['languages'][locale]
&& config.contentTypes[contentType]['languages']['und']
!config.contentTypes[contentType]['languages'][locale] &&
config.contentTypes[contentType]['languages']['und']
) {
locale = 'und';
} else if (
!config.contentTypes[contentType]['languages'][locale]
&& !config.contentTypes[contentType]['languages']['und']
!config.contentTypes[contentType]['languages'][locale] &&
!config.contentTypes[contentType]['languages']['und']
) {
return null;
}

const { pattern } = config.contentTypes[contentType]['languages'][locale];
const path = await strapi.plugins.sitemap.services.pattern.resolvePattern(pattern, page);
const path = await strapi.plugins.sitemap.services.pattern.resolvePattern(
pattern,
page,
);

let hostnameOverride = config.hostname_overrides[page.locale] || '';
hostnameOverride = hostnameOverride.replace(/\/+$/, '');
const url = `${hostnameOverride}${path}`;
Expand All @@ -91,11 +107,19 @@ const getSitemapPageData = async (config, page, contentType) => {
lastmod: page.updatedAt,
url: url,
links: await getLanguageLinks(config, page, contentType, url),
changefreq: config.contentTypes[contentType]['languages'][locale].changefreq || 'monthly',
priority: parseFloat(config.contentTypes[contentType]['languages'][locale].priority) || 0.5,
changefreq:
config.contentTypes[contentType]['languages'][locale].changefreq ||
'monthly',
priority:
parseFloat(
config.contentTypes[contentType]['languages'][locale].priority,
) || 0.5,
};

if (config.contentTypes[contentType]['languages'][locale].includeLastmod === false) {
if (
config.contentTypes[contentType]['languages'][locale].includeLastmod ===
false
) {
delete pageData.lastmod;
}

Expand All @@ -115,42 +139,55 @@ const createSitemapEntries = async (invalidationObject) => {
const cacheEntries = {};

// Collection entries.
await Promise.all(Object.keys(config.contentTypes).map(async (contentType) => {
if (invalidationObject && !Object.keys(invalidationObject).includes(contentType)) {
return;
}

cacheEntries[contentType] = {};

// Query all the pages
const pages = await getService('query').getPages(config, contentType, invalidationObject?.[contentType]?.ids);

// Add formatted sitemap page data to the array.
await Promise.all(pages.map(async (page, i) => {
const pageData = await getSitemapPageData(config, page, contentType);
if (pageData) {
sitemapEntries.push(pageData);

// Add page to the cache.
cacheEntries[contentType][page.id] = pageData;
await Promise.all(
Object.keys(config.contentTypes).map(async (contentType) => {
if (
invalidationObject &&
!Object.keys(invalidationObject).includes(contentType)
) {
return;
}
}));

}));

cacheEntries[contentType] = {};

// Query all the pages
const pages = await getService('query').getPages(
config,
contentType,
invalidationObject?.[contentType]?.ids,
);

// Add formatted sitemap page data to the array.
await Promise.all(
pages.map(async (page, i) => {
const pageData = await getSitemapPageData(config, page, contentType);
if (pageData) {
sitemapEntries.push(pageData);

// Add page to the cache.
cacheEntries[contentType][page.id] = pageData;
}
}),
);
}),
);

// Custom entries.
await Promise.all(Object.keys(config.customEntries).map(async (customEntry) => {
sitemapEntries.push({
url: customEntry,
changefreq: config.customEntries[customEntry].changefreq,
priority: parseFloat(config.customEntries[customEntry].priority),
});
}));
await Promise.all(
Object.keys(config.customEntries).map(async (customEntry) => {
sitemapEntries.push({
url: customEntry,
changefreq: config.customEntries[customEntry].changefreq,
priority: parseFloat(config.customEntries[customEntry].priority),
});
}),
);

// Custom homepage entry.
if (config.includeHomepage) {
const hasHomePage = !isEmpty(sitemapEntries.filter((entry) => entry.url === ''));
const hasHomePage = !isEmpty(
sitemapEntries.filter((entry) => entry.url === ''),
);

// Only add it when no other '/' entry is present.
if (!hasHomePage) {
Expand Down Expand Up @@ -185,12 +222,20 @@ const saveSitemap = async (filename, sitemap, isIndex) => {
type: isIndex ? 'index' : 'default_hreflang',
});
} catch (e) {
strapi.log.error(logMessage(`Something went wrong while trying to write the sitemap XML to the database. ${e}`));
strapi.log.error(
logMessage(
`Something went wrong while trying to write the sitemap XML to the database. ${e}`,
),
);
throw new Error();
}
})
.catch((err) => {
strapi.log.error(logMessage(`Something went wrong while trying to build the sitemap with streamToPromise. ${err}`));
strapi.log.error(
logMessage(
`Something went wrong while trying to build the sitemap with streamToPromise. ${err}`,
),
);
throw new Error();
});
};
Expand All @@ -215,26 +260,28 @@ const getSitemapStream = async (urlCount) => {
}

if (urlCount <= LIMIT) {
return [new SitemapStream({
hostname: config.hostname,
...xslObj,
}), false];
return [
new SitemapStream({
hostname: config.hostname,
...xslObj,
}),
false,
];
} else {
return [
new SitemapAndIndexStream({
limit: LIMIT,
...xslObj,
lastmodDateOnly: false,
getSitemapStream: (i) => {
const sitemapStream = new SitemapStream({
hostname: config.hostname,
...xslObj,
});
const delta = i + 1;
const path = `api/sitemap/index.xml?page=${delta}`;

return [new SitemapAndIndexStream({
limit: LIMIT,
...xslObj,
lastmodDateOnly: false,
getSitemapStream: (i) => {
const sitemapStream = new SitemapStream({
hostname: config.hostname,
...xslObj,
});
const delta = i + 1;
const path = `api/sitemap/index.xml?page=${delta}`;

streamToPromise(sitemapStream)
.then((sm) => {
streamToPromise(sitemapStream).then((sm) => {
getService('query').createSitemap({
sitemap_string: sm.toString(),
name: 'default',
Expand All @@ -243,9 +290,14 @@ const getSitemapStream = async (urlCount) => {
});
});

return [new URL(path, serverUrl || 'http://localhost:1337').toString(), sitemapStream];
},
}), true];
return [
new URL(path, serverUrl || 'http://localhost:1337').toString(),
sitemapStream,
];
},
}),
true,
];
}
};

Expand All @@ -259,23 +311,25 @@ const getSitemapStream = async (urlCount) => {
*/
const createSitemap = async (cache, invalidationObject) => {
const cachingEnabled = strapi.config.get('plugin.sitemap.caching');
const autoGenerationEnabled = strapi.config.get('plugin.sitemap.autoGenerate');
const autoGenerationEnabled = strapi.config.get(
'plugin.sitemap.autoGenerate',
);

try {
const {
sitemapEntries,
cacheEntries,
} = await createSitemapEntries(invalidationObject);
const { sitemapEntries, cacheEntries } = await createSitemapEntries(
invalidationObject,
);
// Format cache to regular entries
const formattedCache = formatCache(cache, invalidationObject);

const allEntries = [
...sitemapEntries,
...formattedCache,
];
const allEntries = [...sitemapEntries, ...formattedCache];

if (isEmpty(allEntries)) {
strapi.log.info(logMessage('No sitemap XML was generated because there were 0 URLs configured.'));
strapi.log.info(
logMessage(
'No sitemap XML was generated because there were 0 URLs configured.',
),
);
return;
}

Expand All @@ -290,16 +344,28 @@ const createSitemap = async (cache, invalidationObject) => {

if (cachingEnabled && autoGenerationEnabled) {
if (!cache) {
getService('query').createSitemapCache(cacheEntries, 'default', sitemapId);
getService('query').createSitemapCache(
cacheEntries,
'default',
sitemapId,
);
} else {
const newCache = mergeCache(cache, cacheEntries);
getService('query').updateSitemapCache(newCache, 'default', sitemapId);
}
}

strapi.log.info(logMessage('The sitemap XML has been generated. It can be accessed on /api/sitemap/index.xml.'));
strapi.log.info(
logMessage(
'The sitemap XML has been generated. It can be accessed on /api/sitemap/index.xml.',
),
);
} catch (err) {
strapi.log.error(logMessage(`Something went wrong while trying to build the SitemapStream. ${err}`));
strapi.log.error(
logMessage(
`Something went wrong while trying to build the SitemapStream. ${err}`,
),
);
throw new Error();
}
};
Expand Down
Loading