fp/services/next/app/lib/vtubers.ts

95 lines
2.5 KiB
TypeScript
Raw Normal View History

2024-01-20 16:16:14 +00:00
import { IVod } from './vods'
2025-01-11 03:10:04 +00:00
import { postgrestLocalUrl, siteUrl } from './constants';
2024-01-20 16:16:14 +00:00
import qs from 'qs';
2024-12-12 07:23:46 +00:00
import { IMeta, IVtuber } from '@futureporn/types';
2024-01-20 16:16:14 +00:00
const fetchVtubersOptions = {
next: {
tags: ['vtubers']
}
}
export function getUrl(slug: string): string {
return `${siteUrl}/vt/${slug}`
}
export async function getVtuberBySlug(slug: string): Promise<IVtuber|null> {
2024-12-12 07:23:46 +00:00
const res = await fetch(`${postgrestLocalUrl}/vtubers?slug=eq.${slug}`);
2024-01-20 16:16:14 +00:00
if (!res.ok) {
console.error(`error inside getVtuberBySlug-- ${res.statusText}`);
return null;
}
2024-12-12 07:23:46 +00:00
const vtubers = await res.json();
return vtubers[0];
2024-01-20 16:16:14 +00:00
}
export async function getVtuberById(id: number): Promise<IVtuber|null> {
2024-12-12 07:23:46 +00:00
const res = await fetch(`${postgrestLocalUrl}/vtubers?id=eq.${id}`);
2024-01-20 16:16:14 +00:00
if (!res.ok) {
console.error(`error inside getVtuberById-- ${res.statusText}`);
return null;
}
const vtuber = await res.json();
return vtuber
}
2024-12-12 07:23:46 +00:00
export async function getVtubers(): Promise<IVtuber[]|null> {
const res = await fetch(`${postgrestLocalUrl}/vtubers`);
2024-01-20 16:16:14 +00:00
if (!res.ok) {
console.error(`error inside getVtubers-- ${res.statusText}`);
return null;
}
const vtubers = await res.json();
return vtubers;
}
export async function getAllVtubers(): Promise<IVtuber[] | null> {
const pageSize = 100;
const allVtubers: IVtuber[] = [];
let currentPage = 1;
while (true) {
2025-01-11 03:10:04 +00:00
const query = new URLSearchParams({
offset: ''+currentPage,
limit: ''+pageSize
}).toString()
2024-01-20 16:16:14 +00:00
try {
2025-01-11 03:10:04 +00:00
console.log(`Getting ${postgrestLocalUrl}/vtubers page=${currentPage}`);
const response = await fetch(`${postgrestLocalUrl}/vtubers?${query}`, fetchVtubersOptions);
2024-01-20 16:16:14 +00:00
if (!response.ok) {
// Handle non-successful response (e.g., HTTP error)
throw new Error(`HTTP error! Status: ${response.status}`);
}
const responseData = await response.json();
if (!responseData.data || responseData.data.length === 0) {
// No more data to fetch
break;
}
allVtubers.push(...responseData.data);
currentPage++;
} catch (error) {
// Handle fetch error
if (error instanceof Error) {
console.error('Error fetching data:', error.message);
}
return null;
}
}
return allVtubers;
}