Skip to content

SeRyKii/pocketbase-typegen

 
 

Repository files navigation

Pocketbase Typegen

Generate typescript definitions from your pocketbase.io schema.

Quickstart

npx pocketbase-typegen --db ./pb_data/data.db --out pocketbase-types.ts

This will produce types for all your PocketBase collections to use in your frontend typescript codebase.

Versions

When using PocketBase > v0.8.x, use pocketbase-typegen v1.1.x

Users of PocketBase < v0.7.x should use pocketbase-typegen v1.0.x

Usage

Options:
  -V, --version          output the version number
  -d, --db <char>        path to the pocketbase SQLite database
  -j, --json <char>      path to JSON schema exported from pocketbase admin UI
  -u, --url <char>       URL to your hosted pocketbase instance. When using this options you must also provide email and password options.
  -e, --email <char>     email for an admin pocketbase user. Use this with the --url option
  -p, --password <char>  password for an admin pocketbase user. Use this with the --url option
  -o, --out <char>       path to save the typescript output file (default: "pocketbase-types.ts")
  -e, --env              flag to use environment variables for configuration, add PB_TYPEGEN_URL, PB_TYPEGEN_EMAIL, PB_TYPEGEN_PASSWORD to your .env file
  -w, --watch            watch for changes in the database and automatically regenerate types, does not work with --json
  -i, --interval <int>   interval in milliseconds to check for changes (default: 5000)
  --hook <char>  custom hook url for checking changes, should return json with timestamp of last change, use with --watch
  -h, --help             display help for command

DB example:

npx pocketbase-typegen --db ./pb_data/data.db

JSON example (export JSON schema from the pocketbase admin dashboard):

npx pocketbase-typegen --json ./pb_schema.json

URL example:

npx pocketbase-typegen --url https://myproject.pockethost.io --email [email protected] --password 'secr3tp@ssword!'

ENV example (add PB_TYPEGEN_URL, PB_TYPEGEN_EMAIL and PB_TYPEGEN_PASSWORD to your .env file):

npx pocketbase-typegen --env

.env:

PB_TYPEGEN_URL=https://myproject.pockethost.io
[email protected]
PB_TYPEGEN_PASSWORD=secr3tp@ssword!

Watch mode example:

npx pocketbase-typegen --db ./pb_data/data.db --watch

npx pocketbase-typegen --url https://myproject.pockethost.io --email admin@myproject --password 'secr3tp@ssword!' --watch

npx pocketbase-typegen --env --watch

Optional flags:

  • --interval - interval in milliseconds to check for changes (default: 5000)
  • --hook - custom hook url for checking changes, should return json with timestamp of last change

example hook javascript code (works on pocketbase version ^0.17.0, add to pb_hooks directory):

watch.pb.js

routerAdd("GET", "/schema/last-update", (c) => {
  try {
    const config = require(`./pb_hooks/config.js`)
    return c.json(200, { timestamp: config.lastTimestamp })
  } catch (err) {
    return c.json(200, { message: err.message })
  }
})

// Hooks for updating lastTimestamp
onModelAfterCreate((_) => {
  const config = require(`./pb_hooks/config.js`)
  config.lastTimestamp = Date.now()
})
onModelAfterUpdate((_) => {
  const config = require(`./pb_hooks/config.js`)
  config.lastTimestamp = Date.now()
})
onModelAfterDelete((_) => {
  const config = require(`./pb_hooks/config.js`)
  config.lastTimestamp = Date.now()
})

config.js:

module.exports = {
  lastTimestamp: 0,
}

Add it to your projects package.json:

"scripts": {
  "typegen": "pocketbase-typegen --db ./pb_data/data.db",
},

Example Output

The output is a typescript file pocketbase-types.ts (example) which will contain:

  • Collections An enum of all collections.
  • [CollectionName]Record One type for each collection (eg ProfilesRecord).
  • [CollectionName]Response One response type for each collection (eg ProfilesResponse) which includes system fields. This is what is returned from the PocketBase API.
    • [CollectionName][FieldName]Options If the collection contains a select field with set values, an enum of the options will be generated.
  • CollectionRecords A type mapping each collection name to the record type.
  • CollectionResponses A type mapping each collection name to the response type.

Example Usage

In PocketBase SDK v0.8+ you can use generic types when fetching records, eg:

import { Collections, TasksResponse } from "./pocketbase-types"

pb.collection(Collections.Tasks).getOne<TasksResponse>("RECORD_ID") // -> results in Promise<TaskResponse>

Example Advanced Usage

You can provide types for JSON fields and expanded relations by passing generic arguments to the Response types:

import { Collections, CommentsResponse, UserResponse } from "./pocketbase-types"

/**
  type CommentsRecord<Tmetadata = unknown> = {
    text: string
    metadata: null | Tmetadata // This is a json field
    user: RecordIdString // This is a relation field
  }
*/
type Tmetadata = {
  likes: number
}
type Texpand = {
  user: UsersResponse
}
const result = await pb
  .collection(Collections.Comments)
  .getOne<CommentsResponse<Tmetadata, Texpand>>("RECORD_ID", { expand: "user" })

// Now you can access the expanded relation with type safety and hints in your IDE
result.expand?.user.username

Status

About

Typescript generation for pocketbase records

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 86.2%
  • JavaScript 10.2%
  • Dockerfile 2.0%
  • Shell 1.6%