|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.io/license |
| 7 | + */ |
| 8 | + |
| 9 | +import {Provider, ɵRuntimeError as RuntimeError} from '@angular/core'; |
| 10 | + |
| 11 | +import {RuntimeErrorCode} from '../../../errors'; |
| 12 | + |
| 13 | +import {IMAGE_LOADER, ImageLoaderConfig} from './image_loader'; |
| 14 | +import {isValidPath, normalizePath, normalizeSrc} from './loader_utils'; |
| 15 | + |
| 16 | +/** |
| 17 | + * Function that generates a built-in ImageLoader for Cloudinary |
| 18 | + * and turns it into an Angular provider. |
| 19 | + * |
| 20 | + * @param path Base URL of your Cloudinary images |
| 21 | + * This URL should match one of the following formats: |
| 22 | + * https://res.cloudinary.com/mysite |
| 23 | + * https://mysite.cloudinary.com |
| 24 | + * https://subdomain.mysite.com |
| 25 | + * @returns Provider that provides an ImageLoader function |
| 26 | + */ |
| 27 | +export function provideCloudinaryLoader(path: string): Provider { |
| 28 | + if (ngDevMode && !isValidPath(path)) { |
| 29 | + throwInvalidPathError(path); |
| 30 | + } |
| 31 | + path = normalizePath(path); |
| 32 | + |
| 33 | + return { |
| 34 | + provide: IMAGE_LOADER, |
| 35 | + useValue: (config: ImageLoaderConfig) => { |
| 36 | + // Example of a Cloudinary image URL: |
| 37 | + // https://res.cloudinary.com/mysite/image/upload/c_scale,f_auto,q_auto,w_600/marketing/tile-topics-m.png |
| 38 | + let params = `f_auto,q_auto`; // sets image format and quality to "auto" |
| 39 | + if (config.width) { |
| 40 | + params += `,w_${config.width}`; |
| 41 | + } |
| 42 | + const url = `${path}/image/upload/${params}/${normalizeSrc(config.src)}`; |
| 43 | + return url; |
| 44 | + } |
| 45 | + }; |
| 46 | +} |
| 47 | + |
| 48 | +function throwInvalidPathError(path: unknown): never { |
| 49 | + throw new RuntimeError( |
| 50 | + RuntimeErrorCode.INVALID_INPUT, |
| 51 | + `CloudinaryLoader has detected an invalid path: ` + |
| 52 | + `expecting a path matching one of the following formats: https://res.cloudinary.com/mysite, https://mysite.cloudinary.com, or https://subdomain.mysite.com - ` + |
| 53 | + `but got: \`${path}\``); |
| 54 | +} |
0 commit comments