PocketBase hook for automatically generating schemas for Zod and pocketbase-ts.
- Download
pb_hooks.zip
from releases and extract it to the same directory as your PocketBase executable. - Update
config.json
if necessary. - Start up the PocketBase server, and it will automatically generate/update the schema file on bootstrap and every time you make changes to the collections.
- If you have
exposeEndpoint
set totrue
, you can access the generated schema through the endpoint you specified inendpointPath
(e.g.https://URL_TO_YOUR_PB_SERVER/schema
).
The generated schema will have field options in docstrings, so you will get additional information like required
, min
, and max
when you hover over properties in your IDE.
JSON fields are typed as any
by default.
You can override this by specifying the type in the overrides
object in your configuration file.
For example, if you have a collection called users
with a JSON field called profile
, you can specify the type like this:
// config.json
{
// ...
"tsSchema": {
// ...
"overrides": {
"users": {
"profile": "{ name: string; age: number }",
},
},
},
// ...
}
Or for more complex types, you can define them in a separate file and import them like this:
// types.ts
export interface UserProfile {
name: string
age: number
}
// config.json
{
// ...
"tsSchema": {
// ...
"overrides": {
"users": {
"profile": "import('./types.ts').UserProfile",
},
},
},
// ...
}
This applies to view collection fields as well.
If you have a view collection and some fields are typed as any
, it is because PocketBase treats them as JSON fields.
You can override them the same way as above.
JSON fields are z.unknown()
by default.
You can override this just like above.
// config.json
{
// ...
"zodSchema": {
// ...
"overrides": {
"users": {
"profile": "z.object({ name: z.string(), age: z.number() })",
},
},
},
}
If you want to define zod schemas in a separate file and import them, you can do it like this:
// zodSchema.ts
export const userProfileSchema = z.object({
name: z.string(),
age: z.number(),
})
// config.json
{
// ...
"zodSchema": {
// ...
"overrides": {
// specify import statements that need to be added to the top of the generated file
"importStatements": ["import { userProfileSchema } from './zodSchema.ts'"],
"users": {
"profile": "userProfileSchema",
},
},
},
}