本文へスキップ
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に貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/pocketbase/pb-hooks/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に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

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル