pb-hooks
它能做什么
这项技能帮你用 JavaScript 编写服务端代码,为 PocketBase 应用扩展功能。适合需要超出内置功能之外逻辑的开发者。
适用场景
- ✓当你需要在 PocketBase 中添加自定义 API 路由时。
- ✓当你希望在记录被创建或更新时运行代码时。
- ✓当你需要定时任务,或从 PocketBase 发出外部 HTTP 请求的时候。
技能链接
https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/pocketbase/pb-hooks/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“请为 PocketBase 编写一个钩子:每当新订单记录被创建时,就给我发一封邮件。”
每周 5 个新技能,1 分钟读完。
工作原理
智能体会在 pb_hooks 文件夹中编写 .pb.js 文件,使用 PocketBase 提供的 JavaScript 引擎,并调用路由、事件、数据库查询和邮件的相关函数。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
PocketBase Server-Side JavaScript (pb_hooks)
Runtime Basics
- Files go in
pb_hooks/*.pb.js(must end with.pb.js) - Engine: goja — ES5.1 + some ES6. No ES6 modules (
import/export), no async/await, no arrow functions in older versions. Usefunction(){}and CommonJSrequire(). - Each file is loaded on app start and on hot-reload
__hooks— absolute path to the pb_hooks directory- TypeScript declarations:
pb_data/types.d.ts(auto-generated, useful for IDE support) --hooksPool=25flag controls concurrent JS goroutines (default: 25)- Each handler runs in an isolated context — no shared mutable state between requests
Routing
Adding routes
routerAdd("GET", "/api/hello/{name}", function(e) {
var name = e.request.pathValue("name")
return e.json(200, { "message": "Hello " + name })
}, /* optional middleware */)
Path patterns
{name}— named path parameter{path...}— wildcard (matches rest of path){$}— exact match (no trailing slash)
Response methods
| Method | Usage |
|---|---|
e.json(status, data) |
JSON response |
e.string(status, text) |
Plain text |
e.html(status, html) |
HTML response |
e.redirect(status, url) |
Redirect (301/302) |
e.blob(status, contentType, bytes) |
Binary data |
e.stream(status, contentType, reader) |
Streaming response |
e.noContent(status) |
No body (204) |
Reading request data
// Body (JSON)
var body = new DynamicModel({ name: "", age: 0 })
e.bindBody(body)
// Query params
var page = e.request.url.query().get("page")
// Headers
var token = e.request.header.get("Authorization")
// Uploaded files
var files = e.findUploadedFiles("document") // returns array of *filesystem.File
// Auth state
var user = e.auth // current auth record or null
var isSuper = e.hasSuperuserAuth()
Middleware
Built-in middleware
routerAdd("GET", "/api/protected", handler,
$apis.requireAuth(), // any authenticated user
// OR
$apis.requireAuth("users"), // only "users" collection
// OR
$apis.requireSuperuserAuth(), // superusers only
// OR
$apis.requireGuestOnly(), // unauthenticated only
// OR
$apis.bodyLimit(5 * 1024 * 1024), // 5MB body limit
// OR
$apis.gzip() // gzip compression
)
Global middleware
routerUse(function(e) {
// runs before every request
console.log(e.request.method, e.request.url.path)
return e.next() // MUST call e.next() to continue
})
Custom route middleware
function myMiddleware(e) {
// pre-processing
var result = e.next() // call next handler
// post-processing
return result
}
routerAdd("GET", "/api/test", handler, myMiddleware)
Priority: middleware runs in order — first registered, first executed.
Event Hooks
Record lifecycle
Each record event has 3 variants:
onRecord*Execute— wraps the default action. Calle.next()to proceed.onRecord*AfterSuccess— runs after successful executiononRecord*AfterError— runs after execution error
// Before/during create
onRecordCreateExecute(function(e) {
// e.record — the record being created
e.record.set("status", "pending")
return e.next() // proceed with creation
}, "posts") // optional collection filter
// After successful create
onRecordAfterCreateSuccess(function(e) {
// e.record — the created record (has ID now)
console.log("Created:", e.record.id)
}, "posts")
// After failed create
onRecordAfterCreateError(function(e) {
// e.error — the error
console.log("Failed:", e.error)
}, "posts")
All record hooks
| Hook | Event object fields |
|---|---|
onRecordCreateExecute |
e.record |
onRecordUpdateExecute |
e.record |
onRecordDeleteExecute |
e.record |
onRecordAfterCreateSuccess |
e.record — after successful create |
onRecordAfterUpdateSuccess |
e.record — after successful update |
onRecordAfterDeleteSuccess |
e.record — after successful delete |
onRecordAfterCreateError |
e.record, e.error — after failed create |
onRecordAfterUpdateError |
e.record, e.error — after failed update |
onRecordAfterDeleteError |
e.record, e.error — after failed delete |
onRecordValidate |
e.record — add custom validation errors |
onRecordEnrich |
e.record — modify API respons |
常见问题
我能使用现代的 JavaScript 特性吗?
不能全部使用。该引擎支持 ES5 和部分 ES6,不支持模块和 async/await。
修改文件后会重新加载吗?
会。钩子文件在应用启动时加载,文件变化时会重新加载。
各个请求的钩子之间共享数据吗?
不共享。每个处理程序在自己的上下文中运行,因此请求之间没有共享状态。
详情
作者的原始描述
Server-side JavaScript hooks for PocketBase (pb_hooks). Use when writing custom routes, event hooks, cron jobs, sending emails, making HTTP requests, querying the database, or extending PocketBase with server-side logic. Covers the goja ES5 runtime, routing, middleware, all event hooks, DB queries, record operations, and global APIs.
热度
- GitHub 星标
- 33k
- 排名
- #8873
- 许可证
- MIT
- 更新时间
- 2026/11/2
评论
- …
同一仓库的更多技能
owasp-security
33k教你的智能体掌握面向网页应用、API、移动端、容器和 AI 智能体的 OWASP 安全指南,以便发现常见弱点并提出修复建议。
agent-management
33k让你的智能体使用 AI Maestro 命令行工具创建、列出、休眠、唤醒、重命名和删除 AI 智能体,管理每个智能体的生命周期。
agent-messaging
33k让你的智能体使用智能体消息协议,在 AI 智能体之间发送、接收和回复带签名的消息,大部分在你自己的电脑上完成。
docs-search
33k让你的智能体搜索自动生成的代码文档,查找函数签名、类定义和注释,从而在修改代码之前核对真实的 API。