this repo has no description
1import { createServerFn } from "@tanstack/react-start";
2import * as v from "valibot";
3import { DB } from "~/data/db";
4import {
5 getPokemonListingQueryLimit,
6 normalizePokemonNameFilter,
7 toPokemonListing,
8} from "~/demos/pokemon-listing/pokemon-listing";
9
10const PokemonListParamsSchema = v.object({
11 offset: v.optional(v.number()),
12});
13
14const FilteredPokemonListParamsSchema = v.object({
15 offset: v.optional(v.number()),
16 nameFilter: v.optional(v.string()),
17});
18
19const innerGetPokemonList = async (offset: number) => {
20 const pokemon = await DB.queries.getPokemonAtOffset(offset, getPokemonListingQueryLimit());
21
22 return toPokemonListing(pokemon, { offset });
23};
24
25const innerGetFilteredPokemonList = async (offset: number, nameFilter: string) => {
26 const appliedFilter = normalizePokemonNameFilter(nameFilter);
27
28 if (!appliedFilter) {
29 return await innerGetPokemonList(offset);
30 }
31
32 const pokemon = await DB.queries.getFilteredPokemonAtOffset(
33 offset,
34 getPokemonListingQueryLimit(),
35 appliedFilter,
36 );
37
38 return toPokemonListing(pokemon, { offset, nameFilter: appliedFilter });
39};
40
41export const getServerPokemonList = createServerFn({ method: "GET" })
42 .inputValidator((params) => {
43 const validated = v.parse(PokemonListParamsSchema, params);
44 const offset = validated.offset ?? 0;
45
46 if (offset < 0) throw new Error("Offset must be greater than or equal to 0");
47
48 return { offset };
49 })
50 .handler(async ({ data }) => {
51 return await innerGetPokemonList(data.offset);
52 });
53
54export const getServerFilteredPokemonList = createServerFn({ method: "GET" })
55 .inputValidator((params) => {
56 const validated = v.parse(FilteredPokemonListParamsSchema, params);
57 const offset = validated.offset ?? 0;
58 const nameFilter = validated.nameFilter ?? "";
59
60 if (offset < 0) throw new Error("Offset must be greater than or equal to 0");
61
62 return { offset, nameFilter };
63 })
64 .handler(async ({ data }) => {
65 return await innerGetFilteredPokemonList(data.offset, data.nameFilter);
66 });