extractRecordOptions(anyZodSchema)
generates automatically a correct object { fields: "...", expand: "..." }
which can be passed to the pocketbase sdk.
We can use the same schema to parse/validate and strongly type the response.
- https://github.com/patmood/pocketbase-typegen
- https://github.com/david-plugge/typed-pocketbase
Contrary to the tools above, this approach is frontend-only. You have to manually keep your zod schemas in sync with your backend collections. However, as I use zod already, I get this for "free", without having to rely on any extra dependencies.
This level of type safety fullfills my needs, but YMMV.
import { page } from '$app/stores'
import { getAppContext } from '$lib/appContext'
import { extractRecordOptions } from '$lib/utils/zod'
import z from 'zod'
const app = getAppContext()
const traitSchema = z.object({
levels: z.record(z.number()),
desc: z.string(),
expand: z.object({
topic: z.object({
label: z.string(),
slug: z.string(),
}),
}),
})
const traitsPromise = (postSlug: string) =>
app.pb
.collection<z.infer<typeof traitSchema>>('traits')
.getFullList({
...extractRecordOptions(traitSchema),
filter: app.pb.filter('post.slug={:slug}', { slug: postSlug }),
})
.then(z.array(traitSchema).parse)