0

I use appwrite to store my images and I get them via a function that I export from 'appwrite.ts'. Then I use Svelte to display the image using the requested brand and name by calling it from the Svelte file, but when the website sees the await, it gives a 500 (Internal Server Error).

+page.svelte

<script lang="ts" type="module">
  import { getImageURL } from '../../../appwrite'
</script>
<img src={(await getImageURL(brand, name))?.toString()} alt="">

appwrite.ts

export async function getImageURL(brand: string, name: string) {
  if (browser) {
    const promise = storage.listFiles('Images', [Query.equal('name', brand + " " + name + ".png")])
    return await promise.then(async function (response) {
      return (endpoint + `/storage/buckets/Images/files/${response.files[0].$id}/view?project=PCDatabase`).toString()
    }), async function (error: any) {
      console.log(error)
      return (endpoint + '/storage/buckets/Images/files/6482e96a92473bfc9b5b/view?project=PCDatabse').toString()
    }
  }
}

I expect the code to work and return the URL without a 500 Error. I've tried removing the await in +page.svelte, but then it gives me back a [object Promise]. How do I fix this?

2 Answers2

1

To await a promise in the template (HTML part), you have to use {#await ...} instead.

See the docs for all syntax variants and examples.

H.B.
  • 166,899
  • 29
  • 327
  • 400
0
  • According to your logic, getImageURL() always has to resolve. So you need to return a Promise that never rejects.

  • For readability it's better to split the functionality to multiple functions. Name the defaults. Avoid repeated code.

const defaultFileId = '6482e96a92473bfc9b5b';

function buildURL(fileId: string = defaultFileId) {
  return `${endpoint}/storage/buckets/Images/files/${fileId}/view?project=PCDatabse`;
}

export function getImageURL(brand: string, name: string): Promise<string> {
  return new Promise((resolve /* , no reject (always resolves) */) => {
    if (!browser) {
      resolve(buildURL(/* no parameter for default */));
      return;
    }
    
    storage.listFiles('Images', [Query.equal('name', `${brand} ${name}.png`)])
    .then((response) => {
      resolve(buildURL(response.files[0].$id));
    })
    .catch((ex) => {
      console.trace(ex);
      resolve(buildURL(/* no parameter for default */));
    });
  });
}
  • Also in the markup section, img tag should be wrapped with #await:
<script lang="ts" type="module">
  import { getImageURL } from '../../../appwrite'
</script>
{#await getImageURL(brand, name)}
  <p>Loading...</p>
{:then url}
  <img src="{url}" alt="">
{/await}
  • A side note: None of the .toString()s is necessary. Those are already strings.
Bulent Vural
  • 2,630
  • 1
  • 13
  • 18