Skip to content

Commit

Permalink
Use Record-based API for cloudinary transformations
Browse files Browse the repository at this point in the history
  • Loading branch information
simonihmig committed Jun 9, 2024
1 parent 2f642a6 commit 4b9fae9
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
30 changes: 24 additions & 6 deletions packages/cdn/src/cloudinary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ export interface CloudinaryConfig {
cloudName: string;
}

type CloudinaryTransformation = Record<string, string | number>;

export interface CloudinaryOptions {
transformations?: string;
transformations?: CloudinaryTransformation | CloudinaryTransformation[];
formats?: ImageType[];
quality?: number;
}
Expand Down Expand Up @@ -46,14 +48,30 @@ export function cloudinaryProvider(
return {
imageTypes: options.formats ?? ['png', 'jpeg', 'webp', 'avif'],
imageUrlFor(width: number, type: ImageType = 'jpeg'): string {
let resizeParams = `w_${width},c_limit,q_${options.quality ?? 'auto'}`;
const resizeParams: CloudinaryTransformation = {
w: width,
c: 'limit',
q: options.quality ?? 'auto',
};
if (deliveryType !== 'upload') {
resizeParams += `,f_${formatMap[type] ?? type}`;
resizeParams['f'] = formatMap[type] ?? type;
}

const params = options.transformations
? `${options.transformations}/${resizeParams}`
: resizeParams;
const transformations = options.transformations
? Array.isArray(options.transformations)
? options.transformations
: [options.transformations]
: [];

transformations.push(resizeParams);

const params = transformations
.map((transformation) =>
Object.entries(transformation)
.map(([key, value]) => `${key}_${value}`)
.join(','),
)
.join('/');

return `https://res.cloudinary.com/${cloudName}/image/${deliveryType}/${params}/${imageId}${
deliveryType === 'upload' ? '.' + type : ''
Expand Down
8 changes: 6 additions & 2 deletions packages/cdn/tests/cloudinary.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ describe('cloudinary', function () {

test('it returns custom params', function () {
const result = cloudinaryProvider('foo/bar.jpg', {
transformations: 'co_rgb:20a020,e_colorize:50',
transformations: { co: 'rgb:20a020', e: 'colorize:50' },
});

expect(result.imageUrlFor(100, 'jpeg')).toBe(
Expand All @@ -55,7 +55,11 @@ describe('cloudinary', function () {

test('it returns custom chained params', function () {
const result = cloudinaryProvider('foo/bar.jpg', {
transformations: 'co_rgb:20a020,e_colorize:50/ar_1.0,c_fill,w_150/r_max',
transformations: [
{ co: 'rgb:20a020', e: 'colorize:50' },
{ ar: '1.0', c: 'fill', w: '150' },
{ r: 'max' },
],
});

expect(result.imageUrlFor(100, 'jpeg')).toBe(
Expand Down

0 comments on commit 4b9fae9

Please sign in to comment.