58 lines
1.8 KiB
TypeScript
58 lines
1.8 KiB
TypeScript
import useSWRInifinite from "swr/infinite";
|
|
import type { Document } from "dbtype/api";
|
|
import { fetcher } from "./fetcher";
|
|
import useSWR from "swr";
|
|
|
|
interface SearchParams {
|
|
word?: string;
|
|
tags?: string;
|
|
limit?: number;
|
|
cursor?: number;
|
|
}
|
|
|
|
function makeSearchParams({
|
|
word, tags, limit, cursor,
|
|
}: SearchParams){
|
|
const search = new URLSearchParams();
|
|
if (word) search.set("word", word);
|
|
if (tags) search.set("allow_tag", tags);
|
|
if (limit) search.set("limit", limit.toString());
|
|
if (cursor) search.set("cursor", cursor.toString());
|
|
return search;
|
|
}
|
|
|
|
export function useSearchGallery(searchParams: SearchParams = {}) {
|
|
return useSWR<Document[]>(`/api/doc/search?${makeSearchParams(searchParams).toString()}`, fetcher);
|
|
}
|
|
|
|
export function useSearchGalleryInfinite(searchParams: SearchParams = {}) {
|
|
return useSWRInifinite<
|
|
{
|
|
data: Document[];
|
|
nextCursor: number | null;
|
|
startCursor: number | null;
|
|
hasMore: boolean;
|
|
}
|
|
>((index, previous) => {
|
|
if (!previous && index > 0) return null;
|
|
if (previous && !previous.hasMore) return null;
|
|
const search = makeSearchParams(searchParams)
|
|
if (index === 0) {
|
|
return `/api/doc/search?${search.toString()}`;
|
|
}
|
|
if (!previous || !previous.data) return null;
|
|
const last = previous.data[previous.data.length - 1];
|
|
search.set("cursor", last.id.toString());
|
|
return `/api/doc/search?${search.toString()}`;
|
|
}, async (url) => {
|
|
const limit = searchParams.limit;
|
|
const res = await fetcher(url);
|
|
return {
|
|
data: res,
|
|
startCursor: res.length === 0 ? null : res[0].id,
|
|
nextCursor: res.length === 0 ? null : res[res.length - 1].id,
|
|
hasMore: limit ? res.length === limit : (res.length === 20),
|
|
};
|
|
});
|
|
}
|
|
|