function getSuitableImageDetails()

in fronts-client/src/util/validateImageSrc.ts [66:117]


function getSuitableImageDetails(
	crops: Crop[],
	id: string,
	desired: Criteria,
): Promise<ImageDescription> {
	const { maxWidth, minWidth, widthAspectRatio, heightAspectRatio } = desired;
	if (crops.length === 0) {
		return Promise.reject(
			new Error(
				typeof widthAspectRatio === 'number' &&
				typeof heightAspectRatio === 'number'
					? `The image does not have a valid ${widthAspectRatio}:${heightAspectRatio} crop on the Grid`
					: `The image does not have any valid crops on the Grid`,
			),
		);
	}
	const assets = sortBy(
		[crops[0].master]
			.concat(crops[0].assets)
			.filter(Boolean)
			.filter((asset) =>
				maxWidth
					? parseInt(`${deepGet(asset, ['dimensions', 'width'])}`, 10) <=
						maxWidth
					: true,
			)
			.filter((asset) =>
				minWidth
					? parseInt(`${deepGet(asset, ['dimensions', 'width'])}`, 10) >=
						minWidth
					: true,
			),
		(asset) => parseInt(`${deepGet(asset, ['dimensions', 'width'])}`, 10) * -1,
	);

	if (assets.length) {
		const mainImageDetails = assets[0];
		const path = mainImageDetails.secureUrl;
		const { height, width } = mainImageDetails.dimensions;
		return Promise.resolve({
			path,
			thumb: assets[assets.length - 1].secureUrl,
			origin: `${urlConstants.media.mediaBaseUrl}/image/${id}`,
			height,
			width,
			ratio: width / height,
		});
	}
	return Promise.reject(
		new Error('The crop does not have a valid asset on the Grid'),
	);
}