2024-08-03 22:33:54 -05:00
|
|
|
import { useState, useEffect } from 'react';
|
|
|
|
import { useQuery } from '@tanstack/react-query';
|
2024-08-04 17:02:34 -05:00
|
|
|
import { useNDKContext } from '@/context/NDKContext';
|
2024-08-09 14:28:57 -05:00
|
|
|
import axios from 'axios';
|
2024-08-03 22:33:54 -05:00
|
|
|
|
2024-08-08 16:29:16 -05:00
|
|
|
const AUTHOR_PUBKEY = process.env.NEXT_PUBLIC_AUTHOR_PUBKEY;
|
2024-08-03 22:33:54 -05:00
|
|
|
|
|
|
|
export function useWorkshopsQuery() {
|
|
|
|
const [isClient, setIsClient] = useState(false);
|
2024-08-04 17:02:34 -05:00
|
|
|
const ndk = useNDKContext();
|
2024-08-03 22:33:54 -05:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setIsClient(true);
|
|
|
|
}, []);
|
|
|
|
|
2024-08-09 14:28:57 -05:00
|
|
|
const hasRequiredProperties = (event, contentIds) => {
|
2024-08-08 16:29:16 -05:00
|
|
|
const hasPlebDevs = event.tags.some(([tag, value]) => tag === "t" && value === "plebdevs");
|
|
|
|
const hasWorkshop = event.tags.some(([tag, value]) => tag === "t" && value === "workshop");
|
2024-08-09 14:28:57 -05:00
|
|
|
const hasId = event.tags.some(([tag, value]) => tag === "d" && contentIds.includes(value));
|
2024-08-08 16:29:16 -05:00
|
|
|
return hasPlebDevs && hasWorkshop && hasId;
|
|
|
|
};
|
|
|
|
|
|
|
|
const fetchWorkshopsFromNDK = async () => {
|
|
|
|
try {
|
2024-08-09 14:28:57 -05:00
|
|
|
const response = await axios.get(`/api/content/all`);
|
|
|
|
const contentIds = response.data;
|
|
|
|
|
|
|
|
if (!contentIds || contentIds.length === 0) {
|
|
|
|
console.log('No content IDs found');
|
|
|
|
return []; // Return early if no content IDs are found
|
2024-08-08 16:29:16 -05:00
|
|
|
}
|
2024-08-09 14:28:57 -05:00
|
|
|
|
2024-08-08 16:29:16 -05:00
|
|
|
await ndk.connect();
|
|
|
|
|
|
|
|
const filter = { kinds: [30023, 30402], authors: [AUTHOR_PUBKEY] };
|
|
|
|
const events = await ndk.fetchEvents(filter);
|
|
|
|
|
|
|
|
if (events && events.size > 0) {
|
|
|
|
const eventsArray = Array.from(events);
|
2024-08-09 14:28:57 -05:00
|
|
|
const workshops = eventsArray.filter(event => hasRequiredProperties(event, contentIds));
|
2024-08-08 16:29:16 -05:00
|
|
|
return workshops;
|
|
|
|
}
|
|
|
|
return [];
|
|
|
|
} catch (error) {
|
|
|
|
console.error('Error fetching workshops from NDK:', error);
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const { data: workshops, isLoading: workshopsLoading, error: workshopsError, refetch: refetchWorkshops } = useQuery({
|
|
|
|
queryKey: ['workshops', isClient],
|
|
|
|
queryFn: fetchWorkshopsFromNDK,
|
2024-08-09 14:28:57 -05:00
|
|
|
// staleTime: 1000 * 60 * 30, // 30 minutes
|
|
|
|
// refetchInterval: 1000 * 60 * 30, // 30 minutes
|
2024-08-08 16:29:16 -05:00
|
|
|
enabled: isClient,
|
|
|
|
});
|
|
|
|
|
|
|
|
return { workshops, workshopsLoading, workshopsError, refetchWorkshops };
|
|
|
|
}
|