Files
image-gateway/examples/js-wrapper.js

71 lines
1.9 KiB
JavaScript
Raw Permalink Normal View History

import crypto from 'node:crypto';
/**
* Утилита для формирования URL imgproxy через Image Gateway.
*
* Используется для:
* - генерации signed URL для imgproxy
* - программного построения URL обработки изображений
*/
const GATEWAY_URL = process.env.IMAGE_GATEWAY_URL ?? 'http://localhost:80';
const KEY = process.env.IMGPROXY_KEY ?? '';
const SALT = process.env.IMGPROXY_SALT ?? '';
function sign(path) {
if (!KEY || !SALT) {
return `${GATEWAY_URL}/unsafe${path}`;
}
const key = Buffer.from(KEY, 'hex');
const salt = Buffer.from(SALT, 'hex');
const hmac = crypto.createHmac('sha256', key);
hmac.update(salt);
hmac.update(path);
const sig = hmac.digest().slice(0, 32).toString('base64url');
return `${GATEWAY_URL}/${sig}${path}`;
}
function encodeSrc(url) {
return Buffer.from(url).toString('base64url');
}
/**
* Формирует URL resize-операции.
*/
export function resize(url, { width, height, quality = 80 }) {
const h = height ?? 0;
const encoded = encodeSrc(url);
const path = `/resize:fit:${width}:${h}:0/q:${quality}/${encoded}`;
return sign(path);
}
/**
* Формирует URL crop-операции.
*/
export function crop(url, { width, height, quality = 80 }) {
const encoded = encodeSrc(url);
const path = `/crop:${width}:${height}:0/q:${quality}/${encoded}`;
return sign(path);
}
/**
* Формирует URL с конвертацией формата.
*/
export function convert(url, { format = 'webp', quality = 80 }) {
const encoded = encodeSrc(url);
const path = `/q:${quality}/${encoded}.${format}`;
return sign(path);
}
/**
* Формирует произвольный URL обработки.
*/
export function custom(url, processingOptions) {
const encoded = encodeSrc(url);
const path = `/${processingOptions}/${encoded}`;
return sign(path);
}