跳到正文
Skillpedia
API 与服务器(后端)33k · #8873

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。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/pocketbase/pb-hooks/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 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. Use function(){} and CommonJS require().
  • 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=25 flag 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. Call e.next() to proceed.
  • onRecord*AfterSuccess — runs after successful execution
  • onRecord*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.

repo: davila7/claude-code-templates

热度

GitHub 星标
33k
排名
#8873
许可证
MIT
更新时间
2026/11/2

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能