pb-hooks
Skill này làm gì
Skill này giúp bạn mở rộng ứng dụng PocketBase bằng mã máy chủ tùy chỉnh viết bằng JavaScript. Skill dành cho lập trình viên cần logic vượt ra ngoài các tính năng có sẵn.
Khi nào nên dùng
- ✓Khi bạn cần một route API tùy chỉnh trong PocketBase.
- ✓Khi bạn muốn mã chạy khi một bản ghi được tạo hoặc cập nhật.
- ✓Khi bạn cần một công việc theo lịch hoặc một yêu cầu HTTP gửi đi từ PocketBase.
Liên kết skill
https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/pocketbase/pb-hooks/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Viết một hook PocketBase gửi email cho tôi mỗi khi có bản ghi đơn hàng mới được tạo.”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Agent viết các file .pb.js trong thư mục pb_hooks, dùng engine JavaScript mà PocketBase cung cấp, với các hàm cho route, sự kiện, truy vấn cơ sở dữ liệu và email.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
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 |
Câu hỏi thường gặp
Tôi có dùng được các tính năng JavaScript hiện đại không?
Không phải tất cả. Engine hỗ trợ ES5 và một phần ES6, còn module và async/await thì không có sẵn.
Nó có tải lại khi tôi đổi file không?
Có. Các file hook được nạp khi ứng dụng khởi động và được tải lại khi chúng thay đổi.
Các yêu cầu có dùng chung dữ liệu giữa các hook không?
Không. Mỗi trình xử lý chạy trong ngữ cảnh riêng, nên không có trạng thái chung giữa các yêu cầu.
Chi tiết
Mô tả gốc của tác giả
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.
Độ phổ biến
- Sao GitHub
- 33k
- Vị trí xếp hạng
- #8873
- Giấy phép
- MIT
- Cập nhật
- 2/11/2026
Bình luận
- …
Thêm skill từ kho mã này
owasp-security
33kDạy agent hướng dẫn bảo mật OWASP cho ứng dụng web, API, di động, container và agent AI, để nhận ra các điểm yếu phổ biến và gợi ý cách sửa.
agent-management
33kCho phép agent của bạn tạo, liệt kê, cho ngủ đông, đánh thức, đổi tên và xóa các agent AI bằng dòng lệnh AI Maestro, quản lý vòng đời của từng agent.
agent-messaging
33kCho phép agent của bạn gửi, nhận và trả lời tin nhắn có chữ ký giữa các agent AI, dùng Agent Messaging Protocol, chủ yếu trên máy của bạn.
docs-search
33kCho phép agent của bạn tìm trong tài liệu code được tạo tự động, như chữ ký hàm, định nghĩa lớp và chú thích, để kiểm tra API thật trước khi sửa code.
Skill tương tự
api-connector-builder
280kGiúp agent của bạn xây dựng kết nối API mới theo đúng mẫu đã có, dùng khi bạn cần thêm một tích hợp mà không tạo cách làm mới.
api-design
280kGiúp agent của bạn thiết kế REST API theo các thực hành tốt nhất, hữu ích để định nghĩa cách API giao tiếp, hiển thị lỗi và tổ chức dữ liệu.
backend-patterns
280kGiúp agent của bạn với các mẫu kiến trúc phía máy chủ và tối ưu cơ sở dữ liệu, hữu ích khi xây dựng hoặc rà soát code chạy trên máy chủ.