All files / app/services url.service.ts

100% Statements 56/56
88.23% Branches 15/17
100% Functions 2/2
100% Lines 56/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 571x 1x 1x 1x 1x 1x 1x 1x 1x 9x 6x 6x 6x 9x 6x 6x 6x 6x 6x 9x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 9x 9x 9x 9x 9x 9x 9x 9x 6x 5x 5x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x  
import { Injectable } from '@angular/core';
 
@Injectable({
	providedIn: 'root',
})
export class UrlService {
	constructor() {}
 
	getNewUrl(url: string): string {
		if (!url || typeof url !== 'string') return '';
 
		// Extract the base URL and parameters
		const urlParts = url.split('/upload/');
		if (urlParts.length < 2) return '';
 
		const [baseUrl, params] = urlParts;
		const parts = params.split('/');
		const transformationsIndex = parts.findIndex((part) => part.match(/v[0-9]+/));
 
		if (transformationsIndex === -1) return '';
 
		// Extract transformations and the rest of the URL
		let transformations = parts.slice(0, transformationsIndex).join(',');
		let restOfUrl = parts.slice(transformationsIndex).join('/');
 
		const supportedFormatsRegex = /\.(png|jpg|jpeg)$/i;
 
		// Replace the supported image format with .webp
		restOfUrl = restOfUrl.replace(supportedFormatsRegex, '.webp');
 
		// Split transformations into an array
		const transformationArray = transformations ? transformations.split(',') : [];
 
		// Define new transformations with specified width and height
		const newTransformations = [`f_auto`, `q_50`];
 
		// Map to replace existing width and height transformations
		const updatedTransformations = transformationArray
			.map((trans) => {
				if (trans.startsWith('w_') || trans.startsWith('h_')) {
					return null; // Mark for removal
				}
				return trans;
			})
			.filter((trans) => trans !== null); // Remove existing width/height
 
		// Merge transformations ensuring unique values
		const mergedTransformations = new Set([...updatedTransformations, ...newTransformations]);
 
		// Reconstruct transformations string
		transformations = Array.from(mergedTransformations).join(',');
 
		// Construct and return the new URL
		return `${baseUrl}/upload/${transformations}/${restOfUrl}`;
	}
}