Create a universal getPlaylistId composable

This commit is contained in:
Maciej Pędzich 2022-09-03 16:25:49 +02:00
parent 2c05fce3c6
commit 7a0b745982
2 changed files with 36 additions and 43 deletions

View File

@ -0,0 +1,15 @@
export const useGetPlaylistId = () => (url: string) => {
const urlObject = new URL(url);
const [collectionName, playlistId] = urlObject.pathname
.split('/')
.filter(Boolean);
const isValidPlaylistUrl =
urlObject.hostname === 'open.spotify.com' &&
collectionName === 'playlist' &&
playlistId;
if (!isValidPlaylistUrl) throw new Error('This is not a valid playlist URL');
return playlistId;
};

View File

@ -6,12 +6,13 @@ import AutoComplete from 'primevue/autocomplete';
import { SearchResult } from '~~/models/search-result';
const router = useRouter();
const getPlaylistId = useGetPlaylistId();
const searchHistory = useLocalStorage('searchHistory', []);
const searchName = ref('');
const suggestions = ref([]);
const suggestions = ref<SearchResult[]>([]);
// For some odd reason, if you don't do JSON.parse(JSON.stringify),
// For some odd reason, if you don't call JSON.parse(JSON.stringify(...)),
// suggestions ref won't get populated.
const displaySearchHistory = () =>
(suggestions.value = JSON.parse(JSON.stringify(searchHistory.value)));
@ -20,16 +21,7 @@ const findPlaylists = async () => {
if (searchName.value.length === 0) return displaySearchHistory();
try {
const urlObject = new URL(searchName.value);
const [collectionName, playlistId] = urlObject.pathname
.split('/')
.filter(Boolean);
if (
urlObject.hostname === 'open.spotify.com' &&
collectionName === 'playlist' &&
playlistId
) {
const playlistId = getPlaylistId(searchName.value);
const searchResults = await $fetch(
`https://raw.githubusercontent.com/mackorone/spotify-playlist-archive/main/playlists/pretty/${playlistId}.json`,
{
@ -45,12 +37,9 @@ const findPlaylists = async () => {
}
).catch((e) => e.data);
return (suggestions.value = searchResults);
} else {
throw new Error('This is not a valid playlist link');
}
suggestions.value = searchResults;
} catch (error) {
if (error.message === 'This is not a valid playlist link') return [];
if (error.message === 'This is not a valid playlist URL') return [];
const searchResults = await $fetch<SearchResult[]>(
`/api/playlists/search?name=${searchName.value}`
@ -90,7 +79,7 @@ const openSnapshotsCalendar = async ({
v-model="searchName"
:suggestions="suggestions"
class="w-full"
placeholder="Start typing, or paste a playlist link"
placeholder="Start typing or paste a playlist URL"
field="name"
:min-length="3"
complete-on-focus
@ -101,14 +90,3 @@ const openSnapshotsCalendar = async ({
</div>
</NuxtLayout>
</template>
<style scoped>
:deep(.p-autocomplete-input) {
width: 100%;
text-align: center;
}
:deep(.p-autocomplete-input::placeholder) {
text-align: center;
}
</style>