const KontentDelivery = require('@kontent-ai/delivery-sdk');
function (context, req) {
let urlSlug = req.body.urlSlug;
const language = req.body.language;
const codename = req.body.codename;
//Get a client for searching content in Kontent AI
const deliveryClient = KontentDelivery.createDeliveryClient({
environmentId: req.body.projectId,
previewApiKey: <ApiKey>,
defaultQueryConfig: {
usePreviewMode: true
}
});
//Request content whose source page is a child page. In the case of a bottom-up tree, request the parent content by its ID
const response = await deliveryClient.items().languageParameter(language).anyFilter('elements.children', [codename]).toPromise();
let parentUrl = '/' + language;
//Exclude the case where the page is a child of itself
if (response.data.items.length) {
response.data.items = response.data.items.filter(x => x.system.codename !== codename);
}
//Get the full parent URL and substitute the current language in case of a language mismatch
if (response.data.items.length) {
const item = response.data.items[0];
if (item.elements.treeurl) {
parentUrl = item.elements.treeurl.value;
}
if (item.system.language !== language) {
const tokens = parentUrl.split('/');
tokens[1] = language;
parentUrl = tokens.join('/');
}
}
//If URL Slug is not provided in the parameters, request it through the client; if unsuccessful, set URL Slug as codename
if (!urlSlug || urlSlug === '') {
const urlSlugResponse = await deliveryClient.item(codename).languageParameter(language).toPromise();
urlSlug = urlSlugResponse.data.item.elements.url.value;
}
if (!urlSlug || urlSlug === '') {
urlSlug = codename;
}
// Generate the final URL by concatenating it with the parent URL and verify its uniqueness
let pageUrl = parentUrl + '/' + urlSlug;
const uniqueResponse = await deliveryClient.items()
.languageParameter(language)
.equalsFilter('elements.treeurl', pageUrl)
.notEqualsFilter('system.id', req.body.contentItemId)
.toPromise();
//If the generated URL is not unique, append the content ID to the end of the URL
if (uniqueResponse.data.items.length) {
pageUrl = pageUrl + '-' + req.body.contentItemId;
}
context.res = {
headers: { "Content-Type": "application/json" },
status: 200,
body: {
success: true,
pageUrl: pageUrl
}
};
}