Skip to content

Commit

Permalink
format scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
JeelRajodiya committed Nov 16, 2024
1 parent 384da22 commit 2935475
Show file tree
Hide file tree
Showing 22 changed files with 1,277 additions and 1,050 deletions.
7 changes: 5 additions & 2 deletions scripts/adopters/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
const { resolve } = require('path');
const writeJSON = require('../utils/readAndWriteJson.js')
const writeJSON = require('../utils/readAndWriteJson.js');

module.exports = async function buildAdoptersList() {
writeJSON('config/adopters.yml',resolve(__dirname, '../../config', 'adopters.json'));
writeJSON(
'config/adopters.yml',
resolve(__dirname, '../../config', 'adopters.json'),
);
};
113 changes: 67 additions & 46 deletions scripts/build-docs.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,40 @@
const sortBy = require('lodash/sortBy')
const sortBy = require('lodash/sortBy');
function buildNavTree(navItems) {
try {
const tree = {
'welcome': {
item: { title: 'Welcome', weight: 0, isRootSection: true, isSection: true, rootSectionId: 'welcome', sectionWeight: 0, slug: '/docs' },
children: {}
}
}
welcome: {
item: {
title: 'Welcome',
weight: 0,
isRootSection: true,
isSection: true,
rootSectionId: 'welcome',
sectionWeight: 0,
slug: '/docs',
},
children: {},
},
};

//first we make sure that list of items lists main section items and then sub sections, documents last
const sortedItems = sortBy(navItems, ['isRootSection', 'weight', 'isSection']);
const sortedItems = sortBy(navItems, [
'isRootSection',
'weight',
'isSection',
]);

sortedItems.forEach(item => {
sortedItems.forEach((item) => {
//identify main sections
if (item.isRootSection) {
tree[item.rootSectionId] = { item, children: {} }
tree[item.rootSectionId] = { item, children: {} };
}

//identify subsections
if (item.parent) {
if (!tree[item.parent]) {
throw new Error(`Parent section ${item.parent} not found for item ${item.title}`);
throw new Error(
`Parent section ${item.parent} not found for item ${item.title}`,
);
}
tree[item.parent].children[item.sectionId] = { item, children: [] };
}
Expand All @@ -29,7 +43,10 @@ function buildNavTree(navItems) {
if (item.sectionId) {
let section = tree[item.rootSectionId]?.children[item.sectionId];
if (!section) {
tree[item.rootSectionId].children[item.sectionId] = { item, children: [] };
tree[item.rootSectionId].children[item.sectionId] = {
item,
children: [],
};
}
tree[item.rootSectionId].children[item.sectionId].children.push(item);
} else {
Expand Down Expand Up @@ -62,40 +79,39 @@ function buildNavTree(navItems) {

// point in slug for specification subgroup to the latest specification version
if (rootKey === 'reference' && key === 'specification') {
allChildren[key].item.href = allChildren[key].children.find(c => c.isPrerelease === undefined).slug;
allChildren[key].item.href = allChildren[key].children.find(
(c) => c.isPrerelease === undefined,
).slug;
}
}
}
}

return tree;

} catch (err) {
throw new Error(`Failed to build navigation tree: ${err.message}`);
}
}

// A recursion function, works on the logic of Depth First Search to traverse all the root and child posts of the
// A recursion function, works on the logic of Depth First Search to traverse all the root and child posts of the
// DocTree to get sequential order of the Doc Posts
const convertDocPosts = (docObject) => {
try {
let docsArray = []
let docsArray = [];
// certain entries in the DocPosts are either a parent to many posts or itself a post.
docsArray.push(docObject?.item || docObject)
docsArray.push(docObject?.item || docObject);
if (docObject.children) {
let children = docObject.children
let children = docObject.children;
Object.keys(children).forEach((child) => {
let docChildArray = convertDocPosts(children[child])
docsArray = [...docsArray, ...docChildArray]
})
let docChildArray = convertDocPosts(children[child]);
docsArray = [...docsArray, ...docChildArray];
});
}
return docsArray
}
catch (err) {
return docsArray;
} catch (err) {
throw new Error('Error in convertDocPosts:', err);
}
}

};

function addDocButtons(docPosts, treePosts) {
let structuredPosts = [];
Expand All @@ -115,68 +131,73 @@ function addDocButtons(docPosts, treePosts) {
});

// Appending the content of welcome page of Docs from the posts.json
structuredPosts[0] = docPosts.filter(p => p.slug === '/docs')[0];
structuredPosts[0] = docPosts.filter((p) => p.slug === '/docs')[0];

// Traversing the structuredPosts in order to add `nextPage` and `prevPage` details for each page
let countDocPages = structuredPosts.length;
structuredPosts = structuredPosts.map((post, index) => {
// post item specifying the root Section or sub-section in the docs are excluded as
// they doesn't comprise any Doc Page or content to be shown in website.
// post item specifying the root Section or sub-section in the docs are excluded as
// they doesn't comprise any Doc Page or content to be shown in website.
if (post?.isRootSection || post?.isSection || index == 0) {
if (post?.isRootSection || index == 0)
rootSections.push(post.title)
return post
if (post?.isRootSection || index == 0) rootSections.push(post.title);
return post;
}

let nextPage = {}, prevPage = {}
let nextPage = {},
prevPage = {};
let docPost = post;

// checks whether the next page for the current docPost item exists or not
if (index + 1 < countDocPages) {
// checks whether the next item inside structuredPosts is a rootElement or a sectionElement
// if yes, it goes again to a next to next item in structuredPosts to link the nextPage
if (!structuredPosts[index + 1].isRootElement && !structuredPosts[index + 1].isSection) {
if (
!structuredPosts[index + 1].isRootElement &&
!structuredPosts[index + 1].isSection
) {
nextPage = {
title: structuredPosts[index + 1].title,
href: structuredPosts[index + 1].slug
}
href: structuredPosts[index + 1].slug,
};
} else {
nextPage = {
title: `${structuredPosts[index + 1].title} - ${structuredPosts[index + 2].title}`,
href: structuredPosts[index + 2].slug
}
href: structuredPosts[index + 2].slug,
};
}
docPost = { ...docPost, nextPage }
docPost = { ...docPost, nextPage };
}

// checks whether the previous page for the current docPost item exists or not
if (index > 0) {
// checks whether the previous item inside structuredPosts is a rootElement or a sectionElement
// if yes, it goes again to a next previous item in structuredPosts to link the prevPage
if (!structuredPosts[index - 1]?.isRootElement && !structuredPosts[index - 1]?.isSection) {
if (
!structuredPosts[index - 1]?.isRootElement &&
!structuredPosts[index - 1]?.isSection
) {
prevPage = {
title: structuredPosts[index - 1].title,
href: structuredPosts[index - 1].slug
}
docPost = { ...docPost, prevPage }
href: structuredPosts[index - 1].slug,
};
docPost = { ...docPost, prevPage };
} else {
// additonal check for the first page of Docs so that it doesn't give any Segementation fault
if (index - 2 >= 0) {
prevPage = {
title: `${structuredPosts[index - 1]?.isRootSection ? rootSections[rootSections.length - 2] : rootSections[rootSections.length - 1]} - ${structuredPosts[index - 2].title}`,
href: structuredPosts[index - 2].slug
href: structuredPosts[index - 2].slug,
};
docPost = { ...docPost, prevPage };
}
}
}
return docPost;
});

} catch (err) {
throw new Error("An error occurred while adding doc buttons:", err);
throw new Error('An error occurred while adding doc buttons:', err);
}
return structuredPosts;
}

module.exports = { buildNavTree, addDocButtons, convertDocPosts }
module.exports = { buildNavTree, addDocButtons, convertDocPosts };
10 changes: 5 additions & 5 deletions scripts/build-meetings.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ async function buildMeetings(writePath) {
try {
auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/calendar'],
credentials: process.env.CALENDAR_SERVICE_ACCOUNT ? JSON.parse(process.env.CALENDAR_SERVICE_ACCOUNT) : undefined,
credentials: process.env.CALENDAR_SERVICE_ACCOUNT
? JSON.parse(process.env.CALENDAR_SERVICE_ACCOUNT)
: undefined,
});

calendar = google.calendar({ version: 'v3', auth });

} catch (err) {
throw new Error(`Authentication failed: ${err.message}`);
}
Expand All @@ -24,10 +25,10 @@ async function buildMeetings(writePath) {
//cron job runs this always on midnight
const currentTime = new Date(Date.now()).toISOString();
const timeMin = new Date(
Date.parse(currentTime) - 100 * 24 * 60 * 60 * 1000
Date.parse(currentTime) - 100 * 24 * 60 * 60 * 1000,
).toISOString();
const timeMax = new Date(
Date.parse(currentTime) + 30 * 24 * 60 * 60 * 1000
Date.parse(currentTime) + 30 * 24 * 60 * 60 * 1000,
).toISOString();

const eventsList = await calendar.events.list({
Expand All @@ -53,7 +54,6 @@ async function buildMeetings(writePath) {
console.log('The following events got fetched', eventsForHuman);

writeFileSync(writePath, eventsForHuman);

} catch (err) {
throw new Error(`Failed to fetch or process events: ${err.message}`);
}
Expand Down
79 changes: 41 additions & 38 deletions scripts/build-newsroom-videos.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,49 +3,52 @@ const { resolve } = require('path');
const fetch = require('node-fetch-2');

async function buildNewsroomVideos(writePath) {
try {
const response = await fetch('https://youtube.googleapis.com/youtube/v3/search?' + new URLSearchParams({
key: process.env.YOUTUBE_TOKEN,
part: 'snippet',
channelId: 'UCIz9zGwDLbrYQcDKVXdOstQ',
eventType: 'completed',
type: 'video',
order: 'Date',
maxResults: 5,
}));

if (!response.ok) {
throw new Error(`HTTP error! with status code: ${response.status}`);
}

const data = await response.json();
console.log(data);

if (!data.items || !Array.isArray(data.items)) {
throw new Error('Invalid data structure received from YouTube API');
}

const videoDataItems = data.items.map((video) => ({
image_url: video.snippet.thumbnails.high.url,
title: video.snippet.title,
description: video.snippet.description,
videoId: video.id.videoId,
}));

const videoData = JSON.stringify(videoDataItems, null, ' ');
console.log('The following are the Newsroom Youtube videos: ', videoData);

writeFileSync(writePath, videoData);

return videoData;
} catch (err) {
throw new Error(`Failed to build newsroom videos: ${err.message}`);
try {
const response = await fetch(
'https://youtube.googleapis.com/youtube/v3/search?' +
new URLSearchParams({
key: process.env.YOUTUBE_TOKEN,
part: 'snippet',
channelId: 'UCIz9zGwDLbrYQcDKVXdOstQ',
eventType: 'completed',
type: 'video',
order: 'Date',
maxResults: 5,
}),
);

if (!response.ok) {
throw new Error(`HTTP error! with status code: ${response.status}`);
}

const data = await response.json();
console.log(data);

if (!data.items || !Array.isArray(data.items)) {
throw new Error('Invalid data structure received from YouTube API');
}

const videoDataItems = data.items.map((video) => ({
image_url: video.snippet.thumbnails.high.url,
title: video.snippet.title,
description: video.snippet.description,
videoId: video.id.videoId,
}));

const videoData = JSON.stringify(videoDataItems, null, ' ');
console.log('The following are the Newsroom Youtube videos: ', videoData);

writeFileSync(writePath, videoData);

return videoData;
} catch (err) {
throw new Error(`Failed to build newsroom videos: ${err.message}`);
}
}

/* istanbul ignore next */
if (require.main === module) {
buildNewsroomVideos(resolve(__dirname, '../config', 'newsroom_videos.json'))
buildNewsroomVideos(resolve(__dirname, '../config', 'newsroom_videos.json'));
}

module.exports = { buildNewsroomVideos };
2 changes: 1 addition & 1 deletion scripts/build-pages.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,4 @@ function copyAndRenameFiles(srcDir, targetDir) {

copyAndRenameFiles(SRC_DIR, TARGET_DIR);

module.exports = {copyAndRenameFiles,capitalizeJsxTags}
module.exports = { copyAndRenameFiles, capitalizeJsxTags };
Loading

0 comments on commit 2935475

Please sign in to comment.