Skip to content

Commit

Permalink
graphql.js : Updated function graphqlAllCampaigns(first,cursor) to ca…
Browse files Browse the repository at this point in the history
…ll getAllCampaigns persisted query with parameters first and cursor

Deleted function  graphqlCampaignPaginated(first,cursor)

Updated gmo-campaign-list/gmo-campaign-list.js : To use persisted query graphqlAllCampaigns(first,cursor) and refactored the pagination to call the decorate function to call the graphql query each time to get the next or previous page
  • Loading branch information
TyroneAEM committed Apr 23, 2024
1 parent 485dbdb commit fcdfcd7
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 198 deletions.
171 changes: 37 additions & 134 deletions blocks/gmo-campaign-list/gmo-campaign-list.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { readBlockConfig } from '../../scripts/lib-franklin.js';
import { decorateIcons } from '../../scripts/lib-franklin.js';
import { graphqlAllCampaigns, graphqlAllCampaignsOffsetLimit, graphqlCampaignPaginated, graphqlCampaignCount } from '../../scripts/graphql.js';
import { graphqlAllCampaigns, graphqlCampaignCount } from '../../scripts/graphql.js';

const icon = 'https://delivery-p108396-e1046543.adobeaemcloud.com/adobe/assets/deliver/urn:aaid:aem:acdaa42f-00ae-42f4-97e5-8309c42d9076/marketing-hub-102023-lockup-video.png'
const testCampaigns = [
Expand Down Expand Up @@ -123,47 +123,22 @@ const testConfig = [
}
]

//Global variables used by helper functions
let currentPageInfo = {};

var cursorArray = [];
var currentPage = 1;
var currentNumberPerPage = 4
let cursorArray = [];
let currentPage = 1;
let currentNumberPerPage = 4
//Get Campaign Count for pagination
const campaignCount = await graphqlCampaignCount();
console.log('campaignCount =',campaignCount);

export default async function decorate(block, numPerPage = currentNumberPerPage, cursor = '', previousPage = false, nextPage = false) {

console.log('currentPage='+currentPage);

const campaignPaginatedResponse = await graphqlCampaignPaginated(numPerPage, cursor);

//Todo Remove console.log
console.log('campaignPaginatedResponse');
console.log(campaignPaginatedResponse);
//Todo Remove console.log

const campaignPaginatedResponse = await graphqlAllCampaigns(numPerPage, cursor);
const campaigns = campaignPaginatedResponse.data.campaignPaginated.edges;

//Todo Delete console.log
console.log('campaigns');
console.log(campaigns);
//Todo Delete console.log


currentPageInfo = campaignPaginatedResponse.data.campaignPaginated.pageInfo;
//Used for repaginate()
currentPageInfo.currentCursor = cursor;
if (previousPage==false && nextPage==false)
if (!previousPage && !nextPage)
{

cursorArray = campaigns.map(item => item.cursor);

//Todo Delete console.log
console.log('cursorArray');
console.log(cursorArray);
//Todo Delete console.log

currentPageInfo.nextCursor = campaigns[campaigns.length - 1].cursor;
}
else if (nextPage){
Expand All @@ -172,24 +147,11 @@ console.log('currentPage='+currentPage);
cursorArray.push(item.cursor);
});

//Todo Delete console.log
console.log('cursorArray');
console.log(cursorArray);
//Todo Delete console.log


currentPageInfo.nextCursor = campaigns[campaigns.length - 1].cursor;

}
currentPageInfo.itemCount = campaigns.length;

//Todo Remove console.log
console.log('currentPageInfo');
console.log(currentPageInfo);
//Todo Remove console.log


//const campaignCount = campaigns.length;
const config = testConfig;
const listHeaders = buildListHeaders(config);
const listItems = buildCampaignList(campaigns, numPerPage);
Expand Down Expand Up @@ -284,7 +246,6 @@ function buildCampaignList(campaigns, numPerPage) {
return listWrapper;
}


function buildProductsList(productList) {
const campaignProducts = document.createElement('div');
const productEl = buildProduct(productList);
Expand Down Expand Up @@ -438,108 +399,50 @@ function buildCurrentPageDivElement(pageNumber,footerPageBtnsWrapper)

function repaginate(dropdown) {
currentNumberPerPage = dropdown.value;
//const numPerPage = dropdown.value;

//Reset current page to 1
currentPage = 1;
const block = document.querySelector('.gmo-campaign-list.block');
decorate(block, currentNumberPerPage, currentPageInfo.currentCursor, false, false);
}

function changePage(targetPage) {
// if targetPage = currentPage, do nothing
const nextBtn = document.querySelector('.footer-pagination-button.next');
const prevBtn = document.querySelector('.footer-pagination-button.prev');
const currentPageBtn = document.querySelector('#current-page');
const currentPage = parseInt(currentPageBtn.dataset.pagenumber);

if (currentPage == targetPage) {
return;
}

const newPageSelector = "[data-pagenumber='" + (targetPage) + "']";
const newPageBtn = document.querySelector(newPageSelector);
const itemsPerPage = document.querySelector('#per-page').value;
const listItems = document.querySelectorAll('.campaign-row');

const lowerBound = ((targetPage * itemsPerPage) - itemsPerPage);
const upperBound = (targetPage * itemsPerPage);

listItems.forEach((row, index) => {
if ((index + 1) <= (lowerBound) || (index + 1) > (upperBound)) {
row.classList.add('hidden');
} else {
row.classList.remove('hidden');
}
})
const totalPages = document.querySelector('.list-footer.footer-wrapper').dataset.pages;
const totalResults = document.querySelector('.list-items').dataset.totalresults;

const pagesText = `Page ${targetPage} of ${totalPages} -- ${totalResults} total results`;
document.querySelector('.footer-total').textContent = pagesText;
if (totalPages == targetPage) {
nextBtn.classList.remove('active')
} else {
nextBtn.classList.add('active');
}
if (targetPage == "1") {
prevBtn.classList.remove('active')
} else {
prevBtn.classList.add('active');
}
currentPageBtn.id = '';
currentPageBtn.classList.remove('currentpage');
newPageBtn.id = 'current-page';
newPageBtn.classList.add('currentpage');
//Reset cursor to ''
decorate(block, currentNumberPerPage, '', false, false);
}

function nextPage(nextBtn) {

console.log('currentPageInfo');
console.log(currentPageInfo);
//Calculate Next Page
currentPage++;
if (currentPageInfo.hasNextPage) {
//Calculate Next Page
currentPage++;

const block = document.querySelector('.gmo-campaign-list.block');
decorate(block, currentNumberPerPage, currentPageInfo.nextCursor, false, true);
const block = document.querySelector('.gmo-campaign-list.block');

decorate( block, currentNumberPerPage, currentPageInfo.nextCursor, false, true);

/*Todo my test code*/
if (!(nextBtn.classList.contains('active'))) {
return;
}
const prevBtn = document.querySelector('.footer-pagination-button.prev');
prevBtn.classList.add('active');

if (!(nextBtn.classList.contains('active'))) {
return;
}


const prevBtn = document.querySelector('.footer-pagination-button.prev');
prevBtn.classList.add('active');
}

function prevPage(prevBtn) {
/*Todo my test code*/
currentPage--;
const offset = currentPage * 4;
const limit = 4;


const block = document.querySelector('.gmo-campaign-list.block');

//Calculate cursor for previous page
const indexCursor = cursorArray.indexOf(currentPageInfo.nextCursor) - currentPageInfo.itemCount - currentNumberPerPage;
console.log('cursor index =', indexCursor);

decorate(block, currentNumberPerPage, cursorArray[indexCursor], true, false);


/*Todo my test code*/

if (!(prevBtn.classList.contains('active'))) {
return;
if (currentPageInfo.hasPreviousPage) {
currentPage--;

const block = document.querySelector('.gmo-campaign-list.block');
//Calculate cursor for previous page
const indexCursor = cursorArray.indexOf(currentPageInfo.nextCursor) - currentPageInfo.itemCount - currentNumberPerPage;
decorate(block, currentNumberPerPage, cursorArray[indexCursor], true, false);
if (!(prevBtn.classList.contains('active'))) {
return;
}
const nextBtn = document.querySelector('.footer-pagination-button.next');
const currentPageBtn = document.querySelector('#current-page');
const currentPageValue = parseInt(currentPageBtn.dataset.pagenumber);
const targetPage = (currentPageValue - 1);

nextBtn.classList.add('active');
}
const nextBtn = document.querySelector('.footer-pagination-button.next');
const currentPageBtn = document.querySelector('#current-page');
const currentPageValue = parseInt(currentPageBtn.dataset.pagenumber);
const targetPage = (currentPageValue - 1);
//changePage(targetPage)
nextBtn.classList.add('active');
}

function sortColumn(dir, property) {
Expand Down
65 changes: 1 addition & 64 deletions scripts/graphql.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,6 @@
import { getBearerToken } from './security.js';
import { getAdminConfig } from './site-config.js';

export async function graphqlAllCampaigns() {

const baseApiUrl = `${await getGraphqlEndpoint()}/graphql/execute.json`;
const projectId = 'gmo';
const queryName = 'getAllCampaigns'; //Todo Shivani will rename query to allCampaigns
const graphqlEndpoint = `${baseApiUrl}/${projectId}/${queryName};offset=0;limit=15;`;
const jwtToken = await getBearerToken();

// Return the fetch promise chain so that it can be awaited outside
return fetch(graphqlEndpoint, {
method: 'GET',
headers: {
Authorization: jwtToken,
},
}).then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
}).then(data => {
return data; // Make sure to return the data so that the promise resolves with it
}).catch(error => {
console.error('Error fetching data: ', error);
throw error; // Rethrow or handle error as appropriate
});
}




export async function graphqlCampaignCount() {
const baseApiUrl = `${await getGraphqlEndpoint()}/graphql/execute.json`;
const projectId = 'gmo';
Expand Down Expand Up @@ -66,8 +36,7 @@ export async function graphqlCampaignCount() {

}


export async function graphqlCampaignPaginated(first,cursor) {
export async function graphqlAllCampaigns(first,cursor) {
const baseApiUrl = `${await getGraphqlEndpoint()}/graphql/execute.json`;
const projectId = 'gmo';
const queryName = 'getAllCampaigns';
Expand Down Expand Up @@ -106,36 +75,6 @@ export async function graphqlCampaignPaginated(first,cursor) {

}




export async function graphqlAllCampaignsOffsetLimit(offset,limit) {

const baseApiUrl = `${await getGraphqlEndpoint()}/graphql/execute.json`;
const projectId = 'gmo';
const queryName = 'getCampaigns';
const graphqlEndpoint = `${baseApiUrl}/${projectId}/${queryName};offset=${offset};limit=${limit};`;
const jwtToken = await getBearerToken();

// Return the fetch promise chain so that it can be awaited outside
return fetch(graphqlEndpoint, {
method: 'GET',
headers: {
Authorization: jwtToken,
},
}).then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
}).then(data => {
return data; // Make sure to return the data so that the promise resolves with it
}).catch(error => {
console.error('Error fetching data: ', error);
throw error; // Rethrow or handle error as appropriate
});
}

export async function graphqlCampaignByName(campaignName) {

const baseApiUrl = `${await getGraphqlEndpoint()}/graphql/execute.json`;
Expand Down Expand Up @@ -196,8 +135,6 @@ export async function graphqlFilterOnMarketingInitiative(marketingInitiative) {
});
}



async function getGraphqlEndpoint() {
const result = await getAdminConfig();
return result.aemGraphqlEndpoint;
Expand Down

0 comments on commit fcdfcd7

Please sign in to comment.