
Product
Introducing Scala and Kotlin Support in Socket
Socket now supports Scala and Kotlin, bringing AI-powered threat detection to JVM projects with easy manifest generation and fast, accurate scans.
pocketbase-ts
Advanced tools
Pocketbase SDK wrapper with more readable option syntax and better typings
A small wrapper around the official PocketBase JavaScript SDK that allows you to write options in a more human-readable way, and also types the response for you.
This is how you would normally write options for the PocketBase SDK:
const postsWithAuthorAndComments = await pb.collection('posts').getFullList({
expand: 'author,comments_via_post',
fields: 'id,title,expand.author.id,expand.author.name,expand.comments_via_post.id,expand.comments_via_post.message',
})
Writing options manually like this is very error-prone, and makes the code very hard to read and maintain.
This wrapper allows you to write it like this instead:
const postsWithAuthorAndComments = await pb.collection('posts').getFullList({
fields: ['id', 'title'],
expand: [
{
key: 'author',
fields: ['id', 'name'],
},
{
key: 'comments_via_post',
fields: ['id', 'message'],
},
],
})
It comes with autocomplete for key
, fields
, expand
, filter
, and sort
options, and also properly types the response as:
type PostsWithAuthorAndComments = Pick<Post, 'id' | 'title'> & {
expand: {
author: Pick<User, 'id' | 'name'>
comments_via_post?: Pick<Comment, 'id' | 'message'>[]
}
}
You can try it out in TS Playground
[!IMPORTANT] This package doesn't strictly follow SemVer and treats 1.x.x like 0.x.x as the name
pocketbase-ts
apparently belonged to another package previously and npm didn't let me publish 0.x.x.
npm install pocketbase-ts
pnpm add pocketbase-ts
Except for the features described below (i.e. the query options), everything from the official SDK is left as is.
[!TIP] I recommend using this hook to generate the schema.
It will watch for any changes made to the collections and update the schema file accordingly, keeping everything in sync.
Below is an example of how you would define the schema for this in the PocketBase docs.
interface PocketBaseCollection {
id: string
created: string
updated: string
}
interface User extends PocketBaseCollection {
name: string
}
interface Post extends PocketBaseCollection {
// relation fields are defined as strings because they are IDs of the related items
author: string
title: string
tags: Array<string>
}
interface Tag extends PocketBaseCollection {
name: string
}
interface Comment extends PocketBaseCollection {
post: string
user: string
message: string
}
// you need to use "type" instead of "interface" here
type Schema = {
// collection name as key
users: {
type: User
}
posts: {
type: Post
relations: {
// field name as key
author: User
// add "?" modifier to annotate optional relation fields
tags?: Array<Tag>
}
}
tags: {
type: Tag
}
comments: {
type: Comment
relations: {
post: Post
user: User
}
}
}
Back-relations will automatically be inferred from the schema, so in most cases, you don't need to define them yourself.
However, in some cases, you may need to define them explicitly. See Caveats for more information.
import { PocketBaseTS } from 'pocketbase-ts'
const pb = new PocketBaseTS<Schema>('http://127.0.0.1:8090')
Use it just like you would with the official SDK, but with a more readable option syntax:
const result = await pb.collection('posts').getOne({
// you can specify fields to be returned in the response
fields: ['id', 'title', 'tags'],
expand: [
{
// returns all fields if not specified
key: 'author',
},
{
key: 'comments_via_post',
// you can use `:excerpt` modifier on string fields
fields: ['message:excerpt(20)'],
// nesting `expand` is supported
expand: [
{
key: 'user',
fields: ['name'],
},
],
},
],
})
The result is automatically typed as:
type Result = Pick<Post, 'tags' | 'id' | 'title'> & {
expand: {
author: User
comments_via_post?: (Pick<Comment, 'message'> & {
expand: {
user: Pick<User, 'name'>
}
})[]
}
}
filter
& sort
While you can still write filter
and sort
as string, you can also use the provided $
tagged template literal helper to get intellisense for the field names.
const result = await pb.collection('posts').getFullList({
filter: ({ $ }) => $`${'author.role'} = "admin" && ${'comments_via_post.message'} ?~ 'hello'`,
sort: ({ $ }) => $`${'created'},${'author.name'}`,
expand: [{ key: 'comments_via_post' }],
})
This function is merely there to provide you with intellisense and help mitigate typos. It does not do any type narrowing or validation.
(i.e. the example above will still have ?
modifier on expand
in the response type.)
While PocketBase supports expanding relations up to 6 levels deep, the number of fields increases exponentially with each level.
The performance hit was very noticeable when I tried to set it to 6 even with the simple schema in the example above.
As such, I've set the maximum depth to 2 by default.
However, should you wish to expand further, you can adjust the maximum depth by passing it as the second type argument when instantiating the SDK.
const pb = new PocketBaseTS<Schema, 6>('')
Schema
:interface SchemaDeclaration {
[collectionName: string]: {
type: Record<PropertyKey, any> // collection type
relations?: {
[fieldName: string]: Record<PropertyKey, any> // relation type
}
}
}
expand
Let's say you want to fetch a post with its comments using expand
.
When the post doesn't have any comments, the SDK (or PocketBase itself rather) returns something like this:
{
"id": "1",
"title": "Lorem ipsum",
"tags": ["lorem", "ipsum"],
"created": "2024-01-01T00:00:00.000Z",
"updated": "2024-01-01T00:00:00.000Z"
}
The response will not have
{
"expand": {
"comments_via_post": [],
},
}
// or not even { expand: undefined } for that matter
So you will get a runtime error if you try to access post.expand.comments_via_post
on a post with no comments.
To handle cases like this, the wrapper will add the ?
modifier to expand
itself if all the specified expands are for optional relation fields.
type Response = Post & {
expand?: {
comments_via_post: Comment[]
}
}
// or with multiple optional relations
type Response = Post & {
expand?: {
tags?: Tag[]
comments_via_post?: Comment[]
}
}
If you expand it along with fields that are not optional like author
, expand
will be present regardless of whether the post has comments or not.
So the response will be typed as:
type Response = Post & {
expand: {
author: User
comments_via_post?: Comment[]
}
}
By default, all back-relations are treated as nullable (e.g. Post
may not have any Comment
), and to-many (e.g. comments_via_post
will be of type Comment[]
).
The former can be dealt with by simply adding the non-null assertion operator !
, but the latter is a different story.
If you have a UNIQUE
index constraint on the relation field, the item in expand
will be of type T
instead of T[]
.
In such case, you can override the default behaviour by explicitly defining back-relations yourself in the schema.
type Schema = {
...
users: {
type: User
relations: {
...
- userDetail_via_user?: UserDetail[] // default (implicit/inferred)
+ userDetail_via_user: UserDetail // made non-nullable by removing the `?`
}
}
...
}
In the example above, User
and Tag
have the exact same shape, and there is no way for TypeScript to differentiate between the two.
To make it clear to TypeScript that they are different, you can use the UniqueCollection
utility type provided by this package.
import type { UniqueCollection } from 'pocketbase-ts'
// pass in the collection name as the second type argument to ensure uniqueness
type User = UniqueCollection<{ name: string } & PocketBaseCollection, 'users'>
Without this, TypeScript will confuse back-relations pointing to User
and Tag
and suggest that users
can be expanded with posts_via_tags
, etc.
The response of batch requests (introduced in the official SDK v0.22.0) is not typed, and likely never will be.
There are many cases where it's impossible to know the shape of the request until runtime.
For example:
const batch = pb.createBatch()
for (const user of users) {
if (condition) {
batch.collection('users').update(user.id, { name: '...' })
} else {
batch.collection('users').delete(user.id)
}
}
const response = batch.send()
FAQs
Pocketbase SDK wrapper with more readable option syntax and better typings
The npm package pocketbase-ts receives a total of 9 weekly downloads. As such, pocketbase-ts popularity was classified as not popular.
We found that pocketbase-ts demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket now supports Scala and Kotlin, bringing AI-powered threat detection to JVM projects with easy manifest generation and fast, accurate scans.
Application Security
/Security News
Socket CEO Feross Aboukhadijeh and a16z partner Joel de la Garza discuss vibe coding, AI-driven software development, and how the rise of LLMs, despite their risks, still points toward a more secure and innovative future.
Research
/Security News
Threat actors hijacked Toptal’s GitHub org, publishing npm packages with malicious payloads that steal tokens and attempt to wipe victim systems.