Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Related media store (#1216)

Olga Bulat9f875610700a
diff --git a/src/components/VAudioDetails/VRelatedAudio.vue b/src/components/VAudioDetails/VRelatedAudio.vue
index ba2806aed..97091aedb 100644
--- a/src/components/VAudioDetails/VRelatedAudio.vue
+++ b/src/components/VAudioDetails/VRelatedAudio.vue
@@ -3,28 +3,25 @@
<h4 class="text-base lg:text-3xl mb-6">
{{ $t('audio-details.related-audios') }}
</h4>
- <div v-if="!$fetchState.error" class="flex flex-col gap-8 lg:gap-12 mb-12">
+ <div v-if="!fetchState.isError" class="flex flex-col gap-8 lg:gap-12 mb-12">
<VAudioTrack
- v-for="audio in audios"
+ v-for="audio in media"
:key="audio.id"
:audio="audio"
layout="row"
:size="audioTrackSize"
/>
- <LoadingIcon v-show="$fetchState.pending" />
+ <LoadingIcon v-show="fetchState.isFetching" />
</div>
- <p v-show="!!$fetchState.error">
+ <p v-show="!!fetchState.isError">
{{ $t('media-details.related-error') }}
</p>
</aside>
</template>
<script>
-import { computed, ref } from '@nuxtjs/composition-api'
+import { computed } from '@nuxtjs/composition-api'
-import { AUDIO } from '~/constants/media'
-
-import useRelated from '~/composables/use-related'
import { isMinScreen } from '~/composables/use-media-query'
import LoadingIcon from '~/components/LoadingIcon.vue'
@@ -34,38 +31,25 @@ export default {
name: 'VRelatedAudio',
components: { VAudioTrack, LoadingIcon },
props: {
- audioId: {
- type: String,
+ media: {
+ type: Array,
+ required: true,
+ },
+ fetchState: {
+ type: Object,
required: true,
},
- service: {},
},
/**
* Fetches related audios on `audioId` change
- * @param {object} props
- * @param {string} props.audioId
- * @param {any} props.service
- * @return {{ audios: import('~/composables/types').Ref<import('~/store/types').AudioDetail[]>, audioTrackSize: import('@nuxtjs/composition-api').ComputedRef<"l" | "s"> }}
+ * @return {{audioTrackSize: import('@nuxtjs/composition-api').ComputedRef<"l" | "s"> }}
*/
- setup(props) {
- const mainAudioId = ref(props.audioId)
- const relatedOptions = {
- mediaType: AUDIO,
- mediaId: mainAudioId,
- service: undefined,
- }
- // Using service prop to be able to mock when testing
- if (props.service) {
- relatedOptions.service = props.service
- }
-
+ setup() {
const isMinScreenMd = isMinScreen('md', { shouldPassInSSR: true })
const audioTrackSize = computed(() => {
return isMinScreenMd.value ? 'l' : 's'
})
-
- const { media: audios } = useRelated(relatedOptions)
- return { audioTrackSize, audios }
+ return { audioTrackSize }
},
}
</script>
diff --git a/src/components/VAudioTrack/VAudioTrack.vue b/src/components/VAudioTrack/VAudioTrack.vue
index f7c85303b..55c8361d3 100644
--- a/src/components/VAudioTrack/VAudioTrack.vue
+++ b/src/components/VAudioTrack/VAudioTrack.vue
@@ -257,12 +257,12 @@ export default defineComponent({
const mediaStore = useMediaStore()
if (
route.value.params.id === props.audio.id ||
- mediaStore.getItemById(AUDIO, props.audio.id)
+ mediaStore.getItemById(props.audio.id, AUDIO)
) {
/**
* If switching to any route other than the single result
* route for this track, pause it. Otherwise, let it keep
- * playing to introduce a "seamless" feeling beween the
+ * playing to introduce a "seamless" feeling between the
* search results page and the single result page.
*
* This handles going from the search page to the single
diff --git a/src/components/VGlobalAudioSection/VGlobalAudioSection.vue b/src/components/VGlobalAudioSection/VGlobalAudioSection.vue
index ba442189f..943992f93 100644
--- a/src/components/VGlobalAudioSection/VGlobalAudioSection.vue
+++ b/src/components/VGlobalAudioSection/VGlobalAudioSection.vue
@@ -13,10 +13,11 @@
<script>
import { useRoute, watch, computed } from '@nuxtjs/composition-api'
+import { AUDIO } from '~/constants/media'
import { useActiveAudio } from '~/composables/use-active-audio'
import { useActiveMediaStore } from '~/stores/active-media'
-import { AUDIO } from '~/constants/media'
import { useMediaStore } from '~/stores/media'
+import { useRelatedMediaStore } from '~/stores/media/related-media'
import VIconButton from '~/components/VIconButton/VIconButton.vue'
import VGlobalAudioTrack from '~/components/VAudioTrack/VGlobalAudioTrack.vue'
@@ -32,16 +33,26 @@ export default {
setup() {
const activeMediaStore = useActiveMediaStore()
const mediaStore = useMediaStore()
+ const relatedMediaStore = useRelatedMediaStore()
const route = useRoute()
const activeAudio = useActiveAudio()
/* Active audio track */
-
+ const getAudioItemById = (trackId) => {
+ if (trackId === mediaStore.state.audio?.id) {
+ return mediaStore.state.audio
+ } else {
+ return (
+ mediaStore.getItemById(trackId, AUDIO) ||
+ relatedMediaStore.getItemById(trackId)
+ )
+ }
+ }
const audio = computed(() => {
const trackId = activeMediaStore.id
if (trackId) {
- return mediaStore.getItemById(AUDIO, trackId)
+ return getAudioItemById(trackId)
}
return null
})
diff --git a/src/components/VImageDetails/VRelatedImages.vue b/src/components/VImageDetails/VRelatedImages.vue
index 3eec53c3c..a713a002a 100644
--- a/src/components/VImageDetails/VRelatedImages.vue
+++ b/src/components/VImageDetails/VRelatedImages.vue
@@ -4,50 +4,28 @@
{{ $t('image-details.related-images') }}
</h3>
<VImageGrid
- :images="images"
+ :images="media"
:can-load-more="false"
- :fetch-state="{
- isFetching: $fetchState.pending,
- fetchingError: $fetchState.error,
- }"
+ :fetch-state="fetchState"
/>
</aside>
</template>
<script>
-import { ref } from '@nuxtjs/composition-api'
-
-import useRelated from '~/composables/use-related'
-import { IMAGE } from '~/constants/media'
-
import VImageGrid from '~/components/VImageGrid/VImageGrid.vue'
export default {
name: 'VRelatedImages',
components: { VImageGrid },
props: {
- imageId: {
- type: String,
+ media: {
+ type: Array,
+ required: true,
+ },
+ fetchState: {
+ type: Object,
required: true,
},
- service: {},
- },
- setup(props) {
- const mainImageId = ref(props.imageId)
- const relatedOptions = {
- mediaType: IMAGE,
- mediaId: mainImageId,
- }
- // Using service prop to be able to mock when testing
- if (props.service) {
- relatedOptions.service = props.service
- }
- /**
- * Fetches related images on `imageId` change.
- */
- const { media: images } = useRelated(relatedOptions)
-
- return { images }
},
}
</script>
diff --git a/src/composables/use-fetch-state.ts b/src/composables/use-fetch-state.ts
index b03065bd1..5063705d3 100644
--- a/src/composables/use-fetch-state.ts
+++ b/src/composables/use-fetch-state.ts
@@ -7,6 +7,13 @@ export interface FetchState {
hasStarted?: boolean
isFinished?: boolean
}
+export const initialFetchState: FetchState = {
+ hasStarted: false,
+ isFetching: false,
+ canFetch: true,
+ isFinished: false,
+ fetchingError: null,
+} as const
/* Constants */
@@ -41,11 +48,33 @@ const nonErrorStatuses: Status[] = [
const canFetchStatuses: Status[] = [statuses.IDLE, statuses.SUCCESS]
/* Composable */
+export const useFetchState = (state: FetchState = initialFetchState) => {
+ const initialState: {
+ status: Status
+ fetchError: null | string
+ isFinished: boolean
+ } = {
+ status: statuses.IDLE,
+ fetchError: null,
+ isFinished: false,
+ }
+ if (state) {
+ if (state.isFetching) {
+ initialState.status = statuses.FETCHING
+ } else if (state.fetchingError) {
+ initialState.status = statuses.ERROR
+ initialState.fetchError = state.fetchingError
+ } else if (state.hasStarted) {
+ initialState.status = statuses.SUCCESS
+ }
+ if (state.isFinished) {
+ initialState.isFinished = true
+ }
+ }
-export const useFetchState = (initialState = statuses.IDLE) => {
- const fetchStatus: Ref<Status> = ref(initialState)
- const fetchError: Ref<string | null> = ref(null)
- const isFinished: Ref<boolean> = ref(false)
+ const fetchStatus: Ref<Status> = ref(initialState.status)
+ const fetchError: Ref<string | null> = ref(initialState.fetchError)
+ const isFinished: Ref<boolean> = ref(initialState.isFinished)
watch(fetchStatus, () => {
if (nonErrorStatuses.includes(fetchStatus.value)) {
@@ -54,6 +83,8 @@ export const useFetchState = (initialState = statuses.IDLE) => {
})
const reset = () => {
fetchStatus.value = statuses.IDLE
+ fetchError.value = null
+ isFinished.value = false
}
const startFetching = () => {
fetchStatus.value = statuses.FETCHING
@@ -112,3 +143,26 @@ export const useFetchState = (initialState = statuses.IDLE) => {
reset,
}
}
+
+export const updateFetchState = (
+ initial: FetchState,
+ action: 'end' | 'finish' | 'start' | 'reset',
+ option?: string
+) => {
+ const fetchState = useFetchState(initial)
+ switch (action) {
+ case 'end':
+ fetchState.endFetching(option)
+ break
+ case 'start':
+ fetchState.startFetching()
+ break
+ case 'finish':
+ fetchState.setFinished()
+ break
+ case 'reset':
+ fetchState.reset()
+ break
+ }
+ return fetchState.fetchState
+}
diff --git a/src/composables/use-related.js b/src/composables/use-related.js
deleted file mode 100644
index b5b6218df..000000000
--- a/src/composables/use-related.js
+++ /dev/null
@@ -1,23 +0,0 @@
-import { ref, useFetch } from '@nuxtjs/composition-api'
-
-import { services } from '~/stores/media/services'
-
-export default function useRelated({
- mediaType,
- mediaId,
- service = services[mediaType],
-}) {
- const media = ref([])
- // fetch and fetchState are available as this.$fetch and this.$fetchState
- // in components, so there's no need to export them,
- // see https://composition-api.nuxtjs.org/lifecycle/usefetch/
- // eslint-disable-next-line no-unused-vars
- const { fetch } = useFetch(async () => {
- const data = await service.getRelatedMedia({
- id: mediaId.value,
- })
- media.value = data.results
- })
- fetch()
- return { media }
-}
diff --git a/src/data/media-service.ts b/src/data/media-service.ts
index 5ba92d782..a178a416c 100644
--- a/src/data/media-service.ts
+++ b/src/data/media-service.ts
@@ -2,7 +2,9 @@ import { decodeMediaData } from '~/utils/decode-media-data'
import { VersionedApiService } from '~/data/api-service'
import type { ApiQueryParams, MediaResult } from '~/store/types'
-import type { Media } from '~/models/media'
+import type { DetailFromMediaType, Media } from '~/models/media'
+
+import type { SupportedMediaType } from '~/constants/media'
import type { AxiosResponse } from 'axios'
@@ -61,23 +63,25 @@ class MediaService<T extends Media> {
/**
* Retrieve related media.
- * @param params - object with id of the main media, for which to fetch related media
+ * @param id - object with id of the main media, for which to fetch related media
*/
- async getRelatedMedia(params: { id: string }): Promise<MediaResult<T[]>> {
- if (!params.id) {
+ async getRelatedMedia<T extends SupportedMediaType>(
+ id: string
+ ): Promise<MediaResult<DetailFromMediaType<T>[]>> {
+ if (!id) {
throw new Error(
`MediaService.getRelatedMedia() id parameter required to retrieve related media.`
)
}
const res = (await VersionedApiService.get(
this.mediaType,
- `${params.id}/related`
- )) as AxiosResponse<MediaResult<T[]>>
+ `${id}/related`
+ )) as AxiosResponse<MediaResult<DetailFromMediaType<T>[]>>
return {
...res.data,
results: res.data.results.map((item) =>
decodeMediaData(item, this.mediaType)
- ) as T[],
+ ) as DetailFromMediaType<T>[],
}
}
}
diff --git a/src/locales/po-files/openverse.pot b/src/locales/po-files/openverse.pot
index f6b2bb819..ff329d4e7 100644
--- a/src/locales/po-files/openverse.pot
+++ b/src/locales/po-files/openverse.pot
@@ -4,7 +4,7 @@ msgid ""
msgstr ""
"Project-Id-Version: Openverse \n"
"Report-Msgid-Bugs-To: https://github.com/wordpress/openverse/issues \n"
-"POT-Creation-Date: 2022-04-08T16:46:12+00:00\n"
+"POT-Creation-Date: 2022-04-12T10:22:32+00:00\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
@@ -1078,13 +1078,13 @@ msgid "An error occurred"
msgstr ""
#. Do not translate words between ### ###.
-#: src/pages/image/_id.vue:142
+#: src/pages/image/_id.vue:150
msgctxt "error.image-not-found"
msgid "Couldn't find image with id ###id###"
msgstr ""
#. Do not translate words between ### ###.
-#: src/pages/audio/_id.vue:67
+#: src/pages/audio/_id.vue:73
msgctxt "error.media-not-found"
msgid "Couldn't find ###mediaType### with id ###id###"
msgstr ""
diff --git a/src/pages/audio/_id.vue b/src/pages/audio/_id.vue
index 8baf30d13..93ef57dd2 100644
--- a/src/pages/audio/_id.vue
+++ b/src/pages/audio/_id.vue
@@ -9,7 +9,11 @@
>
<VMediaReuse data-testid="audio-attribution" :media="audio" />
<VAudioDetails data-testid="audio-info" :audio="audio" />
- <VRelatedAudio v-if="audio.id" :audio-id="audio.id" />
+ <VRelatedAudio
+ v-if="audio.id"
+ :media="relatedMedia"
+ :fetch-state="relatedFetchState"
+ />
</div>
</main>
</template>
@@ -19,6 +23,7 @@ import { computed } from '@nuxtjs/composition-api'
import { AUDIO } from '~/constants/media'
import { useMediaStore } from '~/stores/media'
+import { useRelatedMediaStore } from '~/stores/media/related-media'
import VAudioDetails from '~/components/VAudioDetails/VAudioDetails.vue'
import VAudioTrack from '~/components/VAudioTrack/VAudioTrack.vue'
@@ -42,14 +47,13 @@ const AudioDetailPage = {
},
setup() {
const mediaStore = useMediaStore()
+ const relatedMediaStore = useRelatedMediaStore()
const audio = computed(() => mediaStore.state.audio)
- return { audio }
- },
- watch: {
- audio(newAudio) {
- this.id = newAudio.id
- },
+ const relatedMedia = computed(() => relatedMediaStore.media)
+ const relatedFetchState = computed(() => relatedMediaStore.fetchState)
+
+ return { audio, relatedMedia, relatedFetchState }
},
async asyncData({ route, error, app, $pinia }) {
try {
@@ -58,6 +62,8 @@ const AudioDetailPage = {
id: route.params.id,
mediaType: AUDIO,
})
+ const relatedMediaStore = useRelatedMediaStore($pinia)
+ await relatedMediaStore.fetchMedia(AUDIO, route.params.id)
return {
id: route.params.id,
}
diff --git a/src/pages/image/_id.vue b/src/pages/image/_id.vue
index 876d176e2..c541c6c45 100644
--- a/src/pages/image/_id.vue
+++ b/src/pages/image/_id.vue
@@ -69,7 +69,7 @@
:image-height="imageHeight"
:image-type="imageType"
/>
- <VRelatedImages :image-id="imageId" />
+ <VRelatedImages :media="relatedMedia" :fetch-state="relatedFetchState" />
</div>
</template>
@@ -80,6 +80,7 @@ import { computed } from '@nuxtjs/composition-api'
import { IMAGE } from '~/constants/media'
import { useMediaStore } from '~/stores/media'
+import { useRelatedMediaStore } from '~/stores/media/related-media'
import VButton from '~/components/VButton.vue'
import VIcon from '~/components/VIcon/VIcon.vue'
@@ -114,8 +115,13 @@ const VImageDetailsPage = {
},
setup() {
const mediaStore = useMediaStore()
+ const relatedMediaStore = useRelatedMediaStore()
+
const image = computed(() => mediaStore.state.image)
- return { image }
+
+ const relatedMedia = computed(() => relatedMediaStore.media)
+ const relatedFetchState = computed(() => relatedMediaStore.fetchState)
+ return { image, relatedMedia, relatedFetchState }
},
computed: {
sketchFabUid() {
@@ -130,11 +136,13 @@ const VImageDetailsPage = {
async asyncData({ app, error, route, $pinia }) {
const imageId = route.params.id
const mediaStore = useMediaStore($pinia)
+ const relatedMediaStore = useRelatedMediaStore($pinia)
try {
await mediaStore.fetchMediaItem({
id: imageId,
mediaType: IMAGE,
})
+ await relatedMediaStore.fetchMedia(IMAGE, imageId)
return {
imageId: imageId,
}
diff --git a/src/stores/media/index.ts b/src/stores/media/index.ts
index 432de5a78..22412c877 100644
--- a/src/stores/media/index.ts
+++ b/src/stores/media/index.ts
@@ -70,7 +70,7 @@ export const useMediaStore = defineStore('media', () => {
/* Getters */
- const getItemById = (mediaType: SupportedMediaType, id: string) => {
+ const getItemById = (id: string, mediaType: SupportedMediaType) => {
return state.results[mediaType].items[id]
}
/**
diff --git a/src/stores/media/related-media.ts b/src/stores/media/related-media.ts
new file mode 100644
index 000000000..3bae6bac2
--- /dev/null
+++ b/src/stores/media/related-media.ts
@@ -0,0 +1,51 @@
+import { defineStore } from 'pinia'
+
+import {
+ FetchState,
+ initialFetchState,
+ updateFetchState,
+} from '~/composables/use-fetch-state'
+import { services } from '~/stores/media/services'
+import type { DetailFromMediaType, Media } from '~/models/media'
+import type { SupportedMediaType } from '~/constants/media'
+
+interface RelatedMediaState {
+ mainMediaId: null | string
+ media: Media[]
+ fetchState: FetchState
+}
+
+export const useRelatedMediaStore = defineStore('related-media', {
+ state: (): RelatedMediaState => ({
+ mainMediaId: null,
+ fetchState: { ...initialFetchState },
+ media: [],
+ }),
+
+ getters: {
+ getItemById: (state) => (id: string) =>
+ state.media.find((item) => item.id === id),
+ },
+
+ actions: {
+ async fetchMedia(mediaType: SupportedMediaType, id: string) {
+ this.mainMediaId = id
+ this.fetchState = updateFetchState(this.fetchState, 'start')
+ let media: DetailFromMediaType<typeof mediaType>[] = []
+ try {
+ media = (
+ await services[mediaType].getRelatedMedia<typeof mediaType>(id)
+ ).results
+ this.fetchState = updateFetchState(this.fetchState, 'end')
+ } catch (error) {
+ this.fetchState = updateFetchState(
+ this.fetchState,
+ 'end',
+ `Could not fetch related ${mediaType} for id ${id}`
+ )
+ } finally {
+ this.media = media
+ }
+ },
+ },
+})
diff --git a/test/unit/specs/components/related-audios.spec.js b/test/unit/specs/components/related-audios.spec.js
index 3fcf3fca6..b99d77cc0 100644
--- a/test/unit/specs/components/related-audios.spec.js
+++ b/test/unit/specs/components/related-audios.spec.js
@@ -7,9 +7,6 @@ import VRelatedAudio from '~/components/VAudioDetails/VRelatedAudio.vue'
import render from '../../test-utils/render'
const audioResults = [{ id: 'audio1' }, { id: 'audio2' }]
-const serviceMock = {
- getRelatedMedia: jest.fn(() => Promise.resolve({ results: audioResults })),
-}
const localVue = createLocalVue()
localVue.use(Vuex)
@@ -23,8 +20,10 @@ const doRender = async () => {
VRelatedAudio,
{
localVue,
- propsData: { audioId: 'foo', service: serviceMock },
- mocks: { $fetchState: { pending: false, error: null, timestamp: null } },
+ propsData: {
+ media: audioResults,
+ fetchState: { isFetching: false, isError: false },
+ },
stubs: { LoadingIcon: true, VAudioTrack: true },
},
mount
@@ -40,7 +39,5 @@ describe('RelatedAudios', () => {
const audioTracks = wrapper.findAll('vaudiotrack-stub')
expect(audioTracks.length).toEqual(audioResults.length)
-
- expect(serviceMock.getRelatedMedia).toHaveBeenCalledTimes(1)
})
})
diff --git a/test/unit/specs/components/related-images.spec.js b/test/unit/specs/components/related-images.spec.js
index 881d141b2..37e83374b 100644
--- a/test/unit/specs/components/related-images.spec.js
+++ b/test/unit/specs/components/related-images.spec.js
@@ -1,47 +1,29 @@
-import Vuex from 'vuex'
import VueI18n from 'vue-i18n'
import { createLocalVue } from '@vue/test-utils'
import { render, screen } from '@testing-library/vue'
import VRelatedImages from '~/components/VImageDetails/VRelatedImages.vue'
-const serviceMock = jest.fn(() =>
- Promise.resolve({
- results: [
- { id: 'img1', url: 'https://wp.org/img1.jpg' },
- { id: 'img2', url: 'https://wp.org/img2.jpg' },
- ],
- })
-)
-const failedMock = jest.fn(() => Promise.reject('No result'))
-
+const media = [
+ { id: 'img1', url: 'https://wp.org/img1.jpg' },
+ { id: 'img2', url: 'https://wp.org/img2.jpg' },
+]
const localVue = createLocalVue()
-localVue.use(Vuex)
localVue.use(VueI18n)
-// without nbFetching property on $nuxt, Nuxt's `fetch` hook throws an error:
-// [Vue warn]: Error in beforeMount hook (Promise/async):
-// "TypeError: Cannot read property 'nbFetching' of undefined"
-localVue.prototype.$nuxt = {
- nbFetching: 0,
-}
describe('RelatedImage', () => {
let props = null
let options = null
beforeEach(() => {
- props = {
- imageId: 'foo',
- service: { getRelatedMedia: serviceMock },
- }
+ props = { media, fetchState: { isFetching: false } }
options = {
localVue,
propsData: props,
stubs: ['VLicense', 'NuxtLink'],
}
})
- it('should render an image grid', async () => {
- // await `render` to get the component after Nuxt's `fetch` call
- await render(VRelatedImages, options)
+ it('should render an image grid', () => {
+ render(VRelatedImages, options)
expect(screen.getByRole('heading').textContent).toContain(
'image-details.related-images'
@@ -50,10 +32,9 @@ describe('RelatedImage', () => {
expect(screen.queryAllByRole('figure').length).toEqual(2)
})
- it('should not render data service rejects with an error', async () => {
- options.propsData.service.getRelatedMedia = failedMock
- // await `render` to get the component after Nuxt's `fetch` call
- await render(VRelatedImages, options)
+ it('should not render data when media array is empty', () => {
+ options.propsData.media = []
+ render(VRelatedImages, options)
expect(screen.getByRole('heading').textContent).toContain(
'image-details.related-images'
)
diff --git a/test/unit/specs/stores/media-store.spec.js b/test/unit/specs/stores/media-store.spec.js
index 58907862b..a9736c860 100644
--- a/test/unit/specs/stores/media-store.spec.js
+++ b/test/unit/specs/stores/media-store.spec.js
@@ -107,7 +107,7 @@ describe('Media Store', () => {
})
it('getItemById returns undefined if there are no items', () => {
const mediaStore = useMediaStore()
- expect(mediaStore.getItemById(IMAGE, 'foo')).toBe(undefined)
+ expect(mediaStore.getItemById('foo', IMAGE)).toBe(undefined)
})
it('getItemById returns correct item', () => {
const mediaStore = useMediaStore()
@@ -119,7 +119,7 @@ describe('Media Store', () => {
},
},
})
- expect(mediaStore.getItemById(IMAGE, 'foo')).toBe(expectedItem)
+ expect(mediaStore.getItemById('foo', IMAGE)).toBe(expectedItem)
})
it('resultItems returns correct items', () => {