Create helper function for getting asset URL from API

This commit is contained in:
2021-09-26 23:37:33 +02:00
parent bee59dab90
commit c2ce89f049
2 changed files with 25 additions and 3 deletions

View File

@@ -1,13 +1,16 @@
<script lang="ts">
import { getAssetUrl } from '$utils/helpers'
export let id: string
export let alt: string
export let width: number
export let height: number
export let quality: number = 80
export let quality: number = 90
export let sizes: any = {}
export let fit: string = 'inside'
export let format: string = 'jpg'
// TODO:
// - quality
// - sizes
// -- width
// -- height
@@ -15,7 +18,7 @@
<picture class={$$props.class}>
<img
src="{import.meta.env.VITE_API_URL_DEV}/assets/{id}"
src={getAssetUrl(id, width, height, quality, fit, format)}
width={width}
height={height}
alt={alt}

19
src/utils/helpers.ts Normal file
View File

@@ -0,0 +1,19 @@
/**
* Get a Directus asset URL from parameters
*/
export const getAssetUrl = (
id: string,
width: number,
height: number,
quality?: number,
fit: string = 'inside',
format?: string
) => {
let args = ''
// Add arguments to URL if specified
if (quality) args += `&quality=${quality}`
if (format) args += `&format=${format}`
return `${import.meta.env.VITE_API_URL_DEV}/assets/${id}?width=${width}&height=${height}&fit=${fit}${args}`
}