Created
June 16, 2021 10:30
-
-
Save ksdme/2ad87532d6e77655050c747cb73a9ae9 to your computer and use it in GitHub Desktop.
Statically CDN wrapper to resize image, reduce image quality or serve image using webp.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import join from 'url-join' | |
import parse from 'url-parse' | |
interface StaticallyImageOperations { | |
webp?: boolean | |
width?: number | |
height?: number | |
quality?: number | |
} | |
/* | |
Returns a Statically link for the image with transformation | |
operations applied as requested. Ignore the query string on the | |
url. | |
*/ | |
export const image = (url: string, operations?: StaticallyImageOperations) => { | |
// Operations that will be applied to the image. | |
const parameters: string[] = [] | |
// Default to true. | |
if (operations?.webp ?? true) { | |
parameters.push('f=auto') | |
} | |
if (operations?.height) { | |
parameters.push(`h=${operations.height}`) | |
} | |
if (operations?.width) { | |
parameters.push(`w=${operations.width}`) | |
} | |
if (operations?.quality) { | |
parameters.push(`q=${operations.quality}`) | |
} | |
const parsed = parse(url) | |
const domain = parsed.host | |
const path = parsed.pathname | |
// Spec on https://statically.io/ | |
return join( | |
'https://cdn.statically.io/img/', | |
domain, | |
parameters.join(), | |
path, | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment