unitedwardrobe / imgproxy-node

A Node client library to generate urls for imgproxy services.
MIT License
36 stars 8 forks source link

Support generating relative URLs #23

Open onomated opened 1 year ago

onomated commented 1 year ago

This currently throws a TypeError if config.baseUrl is not an absolute URL here. There has been an ongoing debate on adding support for relative URLs to the URL class. My current setup has to work with relative URLs as it's a backing server to multiple domains. It will be great to provide a flexible way to build the final URL.

A suggestion would be to support a url builder function in the config, for example:

export interface ImgproxyConfig {
  baseUrl: string;
  insecure?: boolean | string;
  urlBuilder?: (baseUrl: string, signature: string, uri: string): string
}

To work around this, I provide a placeholder url in the config and replace it after imgproxy url generation. It works great with relative urls:

const imageServerUrl = "/image-server/";
const urlHack = "https://www.example.com/";
const reverseHack = (generatedUrl: string) => {
  if (generatedUrl.startsWith(urlHack)) {
    return `${imageServerUrl}${generatedUrl.substring(urlHack.length)}`;
  }
  return generatedUrl;
};

const imgproxy = new ImageProxy({
  baseUrl: urlHack,
  key,
  salt,
  encode: true,
});

const imgUrl = reverseHack(imgproxy.builder().generateUrl(cdnUrl));