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

Refactoring articleTeaser and authorCard blocks to fetch data from index files #68

Merged
merged 3 commits into from
Jan 16, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
30 changes: 14 additions & 16 deletions cigaradvisor/blocks/article-teaser/article-teaser.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { createOptimizedPicture } from '../../scripts/aem.js';
import { fetchData } from '../../scripts/scripts.js';
import { fetchData, getRelativePath } from '../../scripts/scripts.js';

function formatDate(originalDateString) {
const utcDateString = new Date((originalDateString - 25569) * 86400 * 1000);
const utcDateString = new Date(originalDateString * 1000);
const utcDate = new Date(utcDateString);
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const day = utcDate.getUTCDate();
Expand All @@ -16,20 +16,18 @@ function formatDate(originalDateString) {
export default async function decorate(block) {
const filterPath = block.querySelector('a').getAttribute('href');
block.classList.add('article-teaser');
const fetchUrl = `${window.hlx.codeBasePath}/drafts/Kailas/pagemeta.json`;
const teaserContent = await fetchData(fetchUrl);
const articleInfo = teaserContent.find((obj) => obj.path === filterPath);
const categoryListUrl = `${window.hlx.codeBasePath}/drafts/Kailas/category/category-list.json`;
const categoryListData = await fetchData(categoryListUrl);
const articleCategory = articleInfo.category;
const articleCategoryInfo = categoryListData.find((obj) => obj.category === articleCategory);
const articleCategoryLink = articleCategoryInfo.categoryLink;
const [formattedDate, datetimeAttr] = formatDate(articleInfo.publishedDate).split('|');
const authorNameHyphenSeparated = articleInfo.author.split(' ').join('-');
const authorLink = `${window.hlx.codeBasePath}/author/drafts/${authorNameHyphenSeparated.toLowerCase()}`;
const articleInfo = await fetchData(getRelativePath(filterPath), '/cigaradvisor/posts/query-index.json');
if (!articleInfo) {
return;
}
const articleCategoryLink = articleInfo.category;
const articleCategoryInfo = await fetchData(getRelativePath(articleCategoryLink));
const [formattedDate, datetimeAttr] = formatDate(articleInfo.published).split('|');
const articleAuthorLink = articleInfo.author;
const articleAuthorInfo = await fetchData(getRelativePath(articleAuthorLink), '/cigaradvisor/author/query-index.json');
block.innerHTML = `
<article class="article article-thumbnail">
<a class="article-category" href="${articleCategoryLink}" data-category="${articleCategory}" title="${articleCategory}">${articleCategory}</a>
<a class="article-category" href="${articleCategoryLink}" data-category="${(articleCategoryInfo && articleCategoryInfo.title) ? articleCategoryInfo.title : ''}" title="${(articleCategoryInfo && articleCategoryInfo.title) ? articleCategoryInfo.title : ''}">${(articleCategoryInfo && articleCategoryInfo.title) ? articleCategoryInfo.title : ''}</a>
<div class="article-image">
${createOptimizedPicture(articleInfo.image).outerHTML}
</div>
Expand All @@ -39,13 +37,13 @@ export default async function decorate(block) {
<a class="article-title-link" href="${articleInfo.path}" title="${articleInfo.title}">${articleInfo.title}</a>
</h2>
<div class="article-meta">
<a class="article-authorLink" href="${authorLink}" title="By ${articleInfo.author}">By ${articleInfo.author}</a>
<a class="article-authorLink" href="${articleAuthorLink}" title="By ${(articleAuthorInfo && articleAuthorInfo.name) ? articleAuthorInfo.name : ''}">By ${(articleAuthorInfo && articleAuthorInfo.name) ? articleAuthorInfo.name : ''}</a>
<time class="article-pubdate" datetime="${datetimeAttr}">${formattedDate}</time>
</div>
</articleheader>
<div class="article-preview">
<div class="article-excerpt">
<p><span class="rt-reading-time" style="display: block;"><span class="rt-label rt-prefix">Reading Time: </span> <span class="rt-time">${articleInfo.readingTime}</span></span> ${articleInfo.articleBlurb}</p>
<p><span class="rt-reading-time" style="display: block;"><span class="rt-label rt-prefix">Reading Time: </span> <span class="rt-time">${articleInfo.readingTime}</span></span> ${articleInfo.description}</p>
</div>
<a class="article-read-more read-more" href="${articleInfo.path}" title="Read More">Read More</a>
</div>
Expand Down
13 changes: 1 addition & 12 deletions cigaradvisor/blocks/articleheader/articleheader.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,4 @@
import { fetchData } from '../../scripts/scripts.js';

function getRelativePath(path) {
let relPath = path;
try {
const url = new URL(path);
relPath = url.pathname;
} catch (error) {
// do nothing
}
return relPath;
}
import { fetchData, getRelativePath } from '../../scripts/scripts.js';

export default async function decorate(block) {
const section = document.createElement('section');
Expand Down
55 changes: 22 additions & 33 deletions cigaradvisor/blocks/authorcard/authorcard.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { readBlockConfig, createOptimizedPicture } from '../../scripts/aem.js';
import { isExternal, fetchData } from '../../scripts/scripts.js';
import { isExternal, fetchData, getRelativePath } from '../../scripts/scripts.js';

export default async function decorate(block) {
const configs = readBlockConfig(block);
Expand Down Expand Up @@ -30,42 +30,31 @@

const rightDiv = document.createElement('div');
rightDiv.classList.add('right-column');
// TODO: fetch author details from query-index.xlsx
const fetchUrl = `${window.hlx.codeBasePath}/drafts/Kailas/pagemeta.json`;
const authorContent = await fetchData(fetchUrl);
const authorsObj = [];
[...authors].forEach((authorPage) => {
let authorPath;
try {
const url = new URL(authorPage);
authorPath = url.pathname;
} catch (error) {
authorPath = authorPage;
}
const authorInfo = authorContent.find((obj) => obj.path === authorPath);
if (authorInfo) {
const authorDetails = {
page: authorInfo.path,
name: authorInfo.authorName,
image: authorInfo.authorImage,
};
authorsObj.push(authorDetails);
}
});
const authorWrapperSection = document.createElement('section');
authorWrapperSection.classList.add('author-wrapper');
authorWrapperSection.innerHTML = '';
[...authorsObj].forEach((author) => {
authorWrapperSection.innerHTML
+= `<div class="author-content">
<div class="overlay-image">
${createOptimizedPicture(author.image).outerHTML}
<div class="overlay-content">
<p class="align-center"><a href="${author.page}">${author.name}</a></p>
</div>
</div>
</div>`;
const authorPromises = [...authors].map(async (authorPage) => {
const authorInfo = await fetchData(getRelativePath(authorPage), '/cigaradvisor/author/query-index.json');
if (authorInfo) {
return `<div class="author-content">
<div class="overlay-image">
${createOptimizedPicture(authorInfo.image).outerHTML}
<div class="overlay-content">
<p class="align-center"><a href="${authorInfo.page}">${authorInfo.name}</a></p>
</div>
</div>
</div>`;
}
return ''; // return an empty string if there's no authorInfo
});

Promise.all(authorPromises)
.then((authorContents) => {
authorWrapperSection.innerHTML += authorContents.join('');
})
.catch((error) => {
console.error('Error fetching author info:', error);

Check warning on line 56 in cigaradvisor/blocks/authorcard/authorcard.js

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
});
rightDiv.replaceChildren(authorWrapperSection);
block.append(rightDiv);
}
75 changes: 64 additions & 11 deletions cigaradvisor/scripts/scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,19 +208,72 @@ export function decorateExternalLink(element) {
}

/**
* Simple funtion to fetch json data from query-index.json
* @param {*} url
* @returns jsonData
* Returns the relative path from a given path.
* If the path is a URL, it extracts the pathname.
* @param {string} path - The path to get the relative path from.
* @returns {string} - The relative path.
*/
export async function fetchData(filterPath) {
const fetchUrl = '/query-index.json';
const resp = await fetch(fetchUrl);
let jsonData = '';
if (resp.ok) {
jsonData = await resp.json();
export function getRelativePath(path) {
let relPath = path;
try {
const url = new URL(path);
relPath = url.pathname;
} catch (error) {
// do nothing
}
return relPath;
}

let indexData = '';
let authorIndexData = '';
let articleIndexData = '';
/**
* Fetches data from a specified URL and returns the filtered
* data based on the provided filter path.
* @param {string} filterPath - The path used to filter the data.
* @param {string} [fetchUrl='/query-index.json'] - The URL to fetch the data
* from. Defaults to '/query-index.json'.
* @returns {Promise<Object>} - A promise that resolves to the filtered data object.
*/
export async function fetchData(filterPath, fetchUrl = '/query-index.json') {
let responeData = '';
if (fetchUrl === '/query-index.json') {
if (!indexData) {
const resp = await fetch(fetchUrl);
let jsonData = '';
if (resp.ok) {
jsonData = await resp.json();
}
indexData = jsonData.data;
}
responeData = indexData;
}
if (fetchUrl === '/cigaradvisor/posts/query-index.json') {
if (!articleIndexData) {
const resp = await fetch(fetchUrl);
let jsonData = '';
if (resp.ok) {
jsonData = await resp.json();
}
articleIndexData = jsonData.data;
}
responeData = articleIndexData;
}
if (fetchUrl === '/cigaradvisor/author/query-index.json') {
if (!authorIndexData) {
const resp = await fetch(fetchUrl);
let jsonData = '';
if (resp.ok) {
jsonData = await resp.json();
}
authorIndexData = jsonData.data;
}
responeData = authorIndexData;
}
let filteredData = '';
if (responeData) {
filteredData = responeData.find((obj) => obj.path === filterPath);
}
const responseData = jsonData.data;
const filteredData = responseData.find((obj) => obj.path === filterPath);
return filteredData;
}

Expand Down