useImageFetch.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import {useAsyncData, AsyncData, useFetch, FetchResult} from "#app";
  2. import {useImageManager} from "~/composables/data/useImageManager";
  3. import {ref, Ref} from "@vue/reactivity";
  4. interface useImageFetchReturnType {
  5. fetch: (id: number | null, defaultImage?: string, height?: number, width?: number) => FetchResult<any>
  6. }
  7. export const useImageFetch = (lazy: boolean = false): useImageFetchReturnType => {
  8. const { imageManager } = useImageManager()
  9. const fetch = (
  10. id: number | null, // If id is null, fetch shall return the default value
  11. defaultImage: string = '',
  12. height: number = 0,
  13. width: number = 0
  14. ): FetchResult<any> => useFetch(
  15. // @ts-ignore
  16. async () => {
  17. const image: Ref<String> = ref(defaultImage ? `assets/images/byDefault/${defaultImage}` : '')
  18. if (id !== null) {
  19. try {
  20. image.value = await imageManager.get(id, height, width)
  21. } catch (e) {
  22. console.error(e)
  23. }
  24. }
  25. return image
  26. }
  27. )
  28. return { fetch }
  29. }