Chuyển đến nội dung
Skillpedia
API và máy chủ (backend)33k · #8873

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.md

Sao 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

Hãy dùng skill này để giúp tôi: https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/pocketbase/pb-hooks/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

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. 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
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.

repo: davila7/claude-code-templates

Độ 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

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự