async function findAndProcessOnwardLinks()

in dotcom-rendering/src/client/sIndicator.ts [158:236]


	async function findAndProcessOnwardLinks() {
		// all anchors with hrefs starting with a forward slash
		const allOnwardAnchorElements = Array.from(
			document.querySelectorAll<HTMLElement>(
				`a[href^='/'],a[href^='${DOTCOM}']`,
			),
		);

		const onwardIdToElementsLookup = allOnwardAnchorElements.reduce<
			Record<string, HTMLElement[]>
		>((acc, anchorElem) => {
			const href = anchorElem.getAttribute('href');

			if (
				!href?.match(/\/.+\/\d+\/\w+\/\d+\/.+/gi) ||
				href.endsWith('#comments')
			) {
				// links to a piece rather than other front etc.
				return acc;
			}

			// CAPI ID doesn't have preceding forward slash
			const capiId = href.startsWith(DOTCOM)
				? href.substring(DOTCOM.length)
				: href.substring(1);

			return {
				...acc,
				[capiId]: [...(acc[capiId] ?? []), anchorElem],
			};
		}, {});

		const idsAlreadyLookedUp = Object.keys(idToSyndicatableLookup);
		const idsToRequest = Object.keys(onwardIdToElementsLookup).filter(
			(id) => !idsAlreadyLookedUp.includes(id),
		);

		const batchSize = 10;

		for (let i = 0; i < idsToRequest.length; i += batchSize) {
			const ids = idsToRequest.slice(i, i + batchSize);

			const idsParam = encodeURIComponent(ids.join(','));

			const capiOnwardsResponse = await fetch(
				`https://content.guardianapis.com/search?show-rights=all&api-key=${capiKey}&ids=${idsParam}`,
			).catch(console.error);

			if (!capiOnwardsResponse?.ok) {
				console.error(
					'sIndicator: problem looking up onward links in capi',
					capiOnwardsResponse,
				);
				return;
			}

			const capiOnwardsJson: { response: { results: Content[] } } =
				await capiOnwardsResponse.json();

			for (const lookupId of ids) {
				idToSyndicatableLookup[lookupId] =
					capiOnwardsJson.response.results.find(
						({ id }) => lookupId === id,
					)?.rights.syndicatable === 'true';
			}

			for (const [id, isSyndicatable] of Object.entries(
				idToSyndicatableLookup,
			)) {
				const elements = onwardIdToElementsLookup[id];
				if (!elements) {
					console.warn('No elements found for id', id);
				}
				for (const element of elements ?? []) {
					augmentOnwardAnchor(isSyndicatable)(element);
				}
			}
		}
	}