2023-02-18 00:23:28 +00:00
|
|
|
import { BANDCAMP_USERNAME, USE_REDIS_CACHE } from '$env/static/private';
|
2023-02-14 06:54:54 +00:00
|
|
|
import scrapeIt from 'scrape-it';
|
2023-04-09 21:03:13 +00:00
|
|
|
import type { ScrapeResult } from 'scrape-it';
|
2023-12-09 01:04:31 +00:00
|
|
|
import { redis } from '$lib/server/redis';
|
2023-12-12 00:26:10 +00:00
|
|
|
import type { Album, BandCampResults } from '../types/album';
|
2023-02-14 06:54:54 +00:00
|
|
|
|
|
|
|
|
export async function fetchBandcampAlbums() {
|
|
|
|
|
try {
|
2023-02-18 00:23:28 +00:00
|
|
|
if (USE_REDIS_CACHE) {
|
2023-02-19 06:24:23 +00:00
|
|
|
const cached: string | null = await redis.get('bandcampAlbums');
|
2023-02-18 00:23:28 +00:00
|
|
|
|
|
|
|
|
if (cached) {
|
2023-02-19 06:24:23 +00:00
|
|
|
const response: Album[] = JSON.parse(cached);
|
2024-12-19 18:54:32 +00:00
|
|
|
console.log(`Cache hit!`);
|
2023-02-18 00:23:28 +00:00
|
|
|
const ttl = await redis.ttl('bandcampAlbums');
|
|
|
|
|
|
2024-12-13 21:39:13 +00:00
|
|
|
return { ...response, cacheControl: `max-age=${ttl}` };
|
2023-02-18 00:23:28 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-12-12 00:26:10 +00:00
|
|
|
const { data }: ScrapeResult<BandCampResults> = await scrapeIt(
|
2023-04-09 21:03:13 +00:00
|
|
|
`https://bandcamp.com/${BANDCAMP_USERNAME}`,
|
|
|
|
|
{
|
|
|
|
|
collectionItems: {
|
|
|
|
|
listItem: '.collection-item-container',
|
|
|
|
|
data: {
|
|
|
|
|
url: {
|
|
|
|
|
selector: '.collection-title-details > a.item-link',
|
|
|
|
|
attr: 'href'
|
|
|
|
|
},
|
|
|
|
|
artwork: {
|
|
|
|
|
selector: 'div.collection-item-art-container a img',
|
|
|
|
|
attr: 'src'
|
|
|
|
|
},
|
|
|
|
|
title: {
|
|
|
|
|
selector: 'span.item-link-alt > div.collection-item-title'
|
|
|
|
|
},
|
|
|
|
|
artist: {
|
|
|
|
|
selector: 'span.item-link-alt > div.collection-item-artist'
|
|
|
|
|
}
|
2023-02-14 06:54:54 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-02-19 06:24:23 +00:00
|
|
|
);
|
2023-02-14 06:54:54 +00:00
|
|
|
|
|
|
|
|
const albums: Album[] = data?.collectionItems || [];
|
|
|
|
|
|
|
|
|
|
if (albums && albums?.length > 0) {
|
2023-02-18 00:23:28 +00:00
|
|
|
if (USE_REDIS_CACHE) {
|
|
|
|
|
redis.set('bandcampAlbums', JSON.stringify(albums), 'EX', 43200);
|
|
|
|
|
}
|
2023-02-14 06:54:54 +00:00
|
|
|
return albums;
|
|
|
|
|
} else {
|
2023-04-09 21:03:13 +00:00
|
|
|
return [];
|
2023-02-14 06:54:54 +00:00
|
|
|
}
|
|
|
|
|
} catch (error) {
|
2023-02-17 21:08:12 +00:00
|
|
|
console.error(error);
|
2023-12-15 23:13:59 +00:00
|
|
|
return [];
|
2023-02-14 06:54:54 +00:00
|
|
|
}
|
|
|
|
|
}
|