### Minimal PocketBase Go Application Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt A basic example of initializing PocketBase, registering a static file server, and starting the application. Ensure Go 1.23+ is installed and dependencies are managed with `go mod`. ```go package main import ( "log" "os" "github.com/pocketbase/pocketbase" "github.com/pocketbase/pocketbase/apis" "github.com/pocketbase/pocketbase/core" ) func main() { app := pocketbase.New() app.OnServe().BindFunc(func(se *core.ServeEvent) error { // serves static files from the provided public dir (if exists) se.Router.GET("/{path...}", apis.Static(os.DirFS("./pb_public"), false)) return se.Next() }) if err := app.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Enable and Start Systemd Service Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Commands to enable a Systemd service to start on boot and to start the service immediately. ```bash [root@dev ~]$ systemctl enable pocketbase.service [root@dev ~]$ systemctl start pocketbase ``` -------------------------------- ### Systemd Service File for PocketBase Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example Systemd service file configuration for PocketBase. This allows the application to start and restart automatically. ```ini [Unit] Description = pocketbase [Service] Type = simple User = root Group = root LimitNOFILE = 4096 Restart = always RestartSec = 5s StandardOutput = append:/root/pb/std.log StandardError = append:/root/pb/std.log WorkingDirectory = /root/pb ExecStart = /root/pb/pocketbase serve yourdomain.com [Install] WantedBy = multi-user.target ``` -------------------------------- ### Start PocketBase Production HTTPS Server Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Starts a PocketBase production server with auto-managed TLS using Let's Encrypt. Requires a domain name to be specified. ```bash [root@dev ~]$ /root/pb/pocketbase serve yourdomain.com ``` -------------------------------- ### OnServe Hook Example with Custom Route Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt The OnServe hook is triggered when the app web server starts, enabling the adjustment of options and attachment of new routes or middlewares. This example registers a GET /hello route. ```go package main import ( "log" "net/http" "github.com/pocketbase/pocketbase" "github.com/pocketbase/pocketbase/apis" "github.com/pocketbase/pocketbase/core" ) func main() { app := pocketbase.New() app.OnServe().BindFunc(func(e *core.ServeEvent) error { // register new "GET /hello" route e.Router.GET("/hello", func(e *core.RequestEvent) error { return e.String(200, "Hello world!") }).Bind(apis.RequireAuth()) return e.Next() }) if err := app.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Start PocketBase with Encryption Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Start the PocketBase server using the --encryptionEnv flag, specifying the environment variable that holds the encryption key. This ensures application settings are stored encrypted. ```bash pocketbase serve --encryptionEnv=PB_ENCRYPTION_KEY ``` -------------------------------- ### Registering GET and POST Routes Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Demonstrates how to register a GET route for public access and a POST route requiring authentication. The POST route uses a middleware to enforce authentication. ```go app.OnServe().BindFunc(func(se *core.ServeEvent) error { // register "GET /hello/{name}" route (allowed for everyone) se.Router.GET("/hello/{name}", func(e *core.RequestEvent) error { name := e.Request.PathValue("name") return e.String(http.StatusOK, "Hello " + name) }) // register "POST /api/myapp/settings" route (allowed only for authenticated users) se.Router.POST("/api/myapp/settings", func(e *core.RequestEvent) error { // do something ... return e.JSON(http.StatusOK, map[string]bool{"success": true}) }).Bind(apis.RequireAuth()) return se.Next() }) ``` -------------------------------- ### Set and Get values in App Store Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Demonstrates how to use app.Store() to set and retrieve values. The GetOrSet method is useful for initializing singletons. ```go app.Store().Set("example", 123) v1 := app.Store().Get("example").(int) // 123 v2 := app.Store().GetOrSet("example2", func() any { // this setter is invoked only once unless "example2" is removed // (e.g. suitable for instantiating singletons) return 456 }).(int) // 456 ``` -------------------------------- ### Register Custom GET Route in Go Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Use app.OnServe().BindFunc() to register custom HTTP routes. This example shows how to add a simple GET route that returns 'Hello world!'. ```go app.OnServe().BindFunc(func(se *core.ServeEvent) error { se.Router.GET("/hello", func(e *core.RequestEvent) error { return e.String(http.StatusOK, "Hello world!") }) return se.Next() }) ``` -------------------------------- ### Registering a GET route for any host Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Matches a GET request to a specific path, regardless of the host. ```javascript routerAdd("GET", "/index.html", ...) ``` -------------------------------- ### Initialize PocketBase SDK with Async Auth Store in Flutter Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Initializes the PocketBase client for Flutter, utilizing SharedPreferences for auth persistence. This example demonstrates a basic setup; consider using EncryptedSharedPreferences for enhanced security. ```dart import 'package:pocketbase/pocketbase.dart'; import 'package:shared_preferences/shared_preferences.dart'; // for simplicity we are using a simple SharedPreferences instance // but you can also replace it with its safer EncryptedSharedPreferences alternative final prefs = await SharedPreferences.getInstance(); // initialize the async store final store = AsyncAuthStore( save: (String data) async => prefs.setString('pb_auth', data), initial: prefs.getString('pb_auth'), ); // initialize the PocketBase client // (it is OK to have a single/global instance for the duration of your application) final pb = PocketBase('http://127.0.0.1:8090', authStore: store); ... await pb.collection('users').authWithPassword('test@example.com', '1234567890'); print(pb.authStore.record) ``` -------------------------------- ### Example Log Response (200 OK) Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt A successful response when retrieving a log entry. ```json { "id": "ai5z3aoed6809au", "created": "2024-10-27 09:28:19.524Z", "data": { "auth": "_superusers", "execTime": 2.392327, "method": "GET", "referer": "http://localhost:8090/_/", "remoteIP": "127.0.0.1", "status": 200, "type": "request", "url": "/api/collections/_pbc_2287844090/records?page=1&perPage=1&filter=&fields=id", "userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36", "userIP": "127.0.0.1" }, "message": "GET /api/collections/_pbc_2287844090/records?page=1&perPage=1&filter=&fields=id", "level": 0 } ``` -------------------------------- ### View Collection SQL Query Example Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example SQL query to populate a read-only view collection with aggregated post data. ```sql SELECT posts.id, posts.name, count(comments.id) as totalComments FROM posts LEFT JOIN comments on comments.postId = posts.id GROUP BY posts.id ``` -------------------------------- ### OnBootstrap Hook Example Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt The OnBootstrap hook is triggered during the initialization of main application resources. Accessing the database before e.Next() will cause an error. ```go package main import ( "log" "github.com/pocketbase/pocketbase" "github.com/pocketbase/pocketbase/core" ) func main() { app := pocketbase.New() app.OnBootstrap().BindFunc(func(e *core.BootstrapEvent) error { if err := e.Next(); err != nil { return err } // e.App return nil }) if err := app.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### OnSettingsReload Hook Example Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt The OnSettingsReload hook is triggered whenever the App.Settings() is replaced with a new state. Calling e.App.Settings() after e.Next() retrieves the new state. ```go package main import ( "log" "github.com/pocketbase/pocketbase" "github.com/pocketbase/pocketbase/core" ) func main() { app := pocketbase.New() app.OnSettingsReload().BindFunc(func(e *core.SettingsReloadEvent) error { if err := e.Next(); err != nil { return err } // e.App.Settings() return nil }) if err := app.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Query Builder Example Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Compose SQL queries programmatically using the db query builder methods like Select(), From(), AndWhere(), Limit(), and OrderBy(). ```go users := []struct { Id string `db:"id" json:"id" Email string `db:"email" json:"email" }{} app.DB(). Select("id", "email"). From("users"). AndWhere(dbx.Like("email", "example.com")), Limit(100). OrderBy("created ASC"). All(&users) ``` -------------------------------- ### Reading Path Parameters Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Provides a concise example of how to extract the value of a named path parameter from an incoming request event. ```go id := e.Request.PathValue("id") ``` -------------------------------- ### Minimal Dockerfile for PocketBase Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt A basic Dockerfile using Alpine Linux to build a PocketBase image. Includes arguments for version and installs necessary packages. ```dockerfile FROM alpine:latest ARG PB_VERSION=0.26.6 RUN apk add --no-cache \ unzip \ ca-certificates ``` -------------------------------- ### Local Module Export Example Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Defines a simple utility module 'utils.js' with an exported 'hello' function for use in PocketBase hooks. ```javascript // pb_hooks/utils.js module.exports = { hello: (name) => { console.log("Hello " + name) } } ``` -------------------------------- ### Custom Collection Query for System Collections Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Demonstrates how to build a custom query to fetch system collections, ordered by creation date. Requires importing 'github.com/pocketbase/dbx' and 'github.com/pocketbase/pocketbase/core'. ```Go import ( "github.com/pocketbase/dbx" "github.com/pocketbase/pocketbase/core" ) ... func FindSystemCollections(app core.App) ([]*core.Collection, error) { collections := []*core.Collection{} err := app.CollectionQuery(). AndWhere(dbx.HashExp{"system": true}). OrderBy("created DESC"). All(&collections) if err != nil { return nil, err } return collections, nil } ``` -------------------------------- ### Register Custom GET Route in JavaScript Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Use routerAdd() to register custom HTTP routes in JavaScript. This example adds a GET route that returns 'Hello world!'. ```javascript routerAdd("GET", "/hello", (e) => { return e.string(200, "Hello world!") }) ``` -------------------------------- ### Registering Routes by Host and Path Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Illustrates how to register routes that match specific hosts and paths, including exact path matches and paths with trailing slashes. ```go // match "GET example.com/index.html" se.Router.GET("example.com/index.html") // match "GET /index.html" (for any host) se.Router.GET("/index.html") // match "GET /static/", "GET /static/a/b/c", etc. se.Router.GET("/static/") ``` -------------------------------- ### Path Parameters with Wildcards Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Demonstrates using path parameters, including the wildcard format `{paramName...}` for matching multiple path segments and `{$}` for matching the end of a URL. ```go // match "GET /static/", "GET /static/a/b/c", etc. // (similar to the above but with a named wildcard parameter) se.Router.GET("/static/{path...}") // match only "GET /static/" (if no "/static" is registered, it is 301 redirected) se.Router.GET("/static/{$}") ``` -------------------------------- ### Registering a GET route with a specific host Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Matches a GET request to a specific host and path. ```javascript routerAdd("GET", "example.com/index.html", ...) ``` -------------------------------- ### Filter records where title starts with 'Lorem' Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Applies a wildcard search to the 'title' field for records starting with a specific string. ```plaintext title ~ "Lorem%" ``` -------------------------------- ### Initialize Default Application Settings in Go Migration Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt This Go migration snippet demonstrates how to set default application settings like app name, URL, and log retention. It's useful for initial setup or configuration changes. ```go // migrations/1687801090_initial_settings.go package migrations import ( "github.com/pocketbase/pocketbase/core" m "github.com/pocketbase/pocketbase/migrations" ) func init() { m.Register(func(app core.App) error { settings := app.Settings() // for all available settings fields you could check // https://github.com/pocketbase/pocketbase/blob/develop/core/settings_model.go#L121-L130 settings.Meta.AppName = "test" settings.Meta.AppURL = "https://example.com" settings.Logs.MaxDays = 2 settings.Logs.LogAuthId = true settings.Logs.LogIP = false return app.Save(settings) }, nil) } ``` -------------------------------- ### Registering a GET route as an anonymous wildcard Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Matches any GET request that begins with the specified path prefix, including the prefix itself. ```javascript routerAdd("GET", "/static/", ...) ``` -------------------------------- ### Server-Side Action Using Superuser Client Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Demonstrates how to import and use the pre-initialized superuser client within a server-side action to interact with PocketBase collections. ```javascript import superuserClient from './src/superuser.js' async function serverAction(req, resp) { ... do some extra data validations or handling ... // send a create request as superuser await superuserClient.collection('example').create({ ... }) ``` -------------------------------- ### Load and Render HTML Templates Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Use the template registry to load multiple HTML files and render them with provided data. Ensure template files are correctly specified. ```go import "github.com/pocketbase/pocketbase/tools/template" data := map[string]any{"name": "John"} html, err := template.NewRegistry().LoadFiles( "views/base.html", "views/partial1.html", "views/partial2.html", ).Render(data) ``` -------------------------------- ### Delete Collection Dart Example Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example of how to delete a collection using the PocketBase Dart SDK. Requires authentication as a superuser. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); ... await pb.collection("_superusers").authWithPassword('test@example.com', '1234567890'); await pb.collections.delete('demo'); ``` -------------------------------- ### Delete Collection JavaScript Example Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example of how to delete a collection using the PocketBase JavaScript SDK. Requires authentication as a superuser. ```javascript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); ... await pb.collection("_superusers").authWithPassword('test@example.com', '1234567890'); await pb.collections.delete('demo'); ``` -------------------------------- ### Grouping Routes with Middlewares Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Shows how to create a route group with a base path and apply middlewares to all routes within that group. It also demonstrates creating nested groups. ```go g := se.Router.Group("/api/myapp") // group middleware g.Bind(apis.RequireAuth()) // group routes g.GET("", action1) g.GET("/example/{id}", action2) g.PATCH("/example/{id}", action3).BindFunc( /* custom route specific middleware func */ ) // nested group sub := g.Group("/sub") sub.GET("/sub1", action4) ``` -------------------------------- ### Registering a GET route to match only the exact path Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Matches a GET request only to the exact specified path, indicated by the special `{$}` parameter. ```javascript routerAdd("GET", "/static/{$}", ...) ``` -------------------------------- ### Creating a New Migration File Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example of creating a new blank migration file using the 'migrate create' command. This command is intended for development environments using 'go run'. ```bash // Since the "create" command makes sense only during development, // it is expected the user to be in the app working directory // and to be using "go run" [root@dev app]$ go run . migrate create "your_new_migration" ``` -------------------------------- ### PocketBase Configuration JSON Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example of a full PocketBase configuration file, including settings for SMTP, backups, S3, meta, rate limits, trusted proxy, batch operations, and logs. ```json { "smtp": { "enabled": false, "port": 587, "host": "smtp.example.com", "username": "", "authMethod": "", "tls": true, "localName": "" }, "backups": { "cron": "0 0 * * *", "cronMaxKeep": 3, "s3": { "enabled": false, "bucket": "", "region": "", "endpoint": "", "accessKey": "", "forcePathStyle": false } }, "s3": { "enabled": false, "bucket": "", "region": "", "endpoint": "", "accessKey": "", "forcePathStyle": false }, "meta": { "appName": "Acme", "appURL": "https://example.com", "senderName": "Support", "senderAddress": "support@example.com", "hideControls": false }, "rateLimits": { "rules": [ { "label": "*:auth", "audience": "", "duration": 3, "maxRequests": 2 }, { "label": "*:create", "audience": "", "duration": 5, "maxRequests": 20 }, { "label": "/api/batch", "audience": "", "duration": 1, "maxRequests": 3 }, { "label": "/api/", "audience": "", "duration": 10, "maxRequests": 300 } ], "enabled": false }, "trustedProxy": { "headers": [], "useLeftmostIP": false }, "batch": { "enabled": true, "maxRequests": 50, "timeout": 3, "maxBodySize": 0 }, "logs": { "maxDays": 7, "minLevel": 0, "logIP": true, "logAuthId": false } } ``` -------------------------------- ### Registering a GET route with a named path parameter Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Matches a GET request to a path that includes a named parameter, such as a user's name. ```javascript routerAdd("GET", "/customers/{name}", ...) ``` -------------------------------- ### Register Middlewares with Priority and ID Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Demonstrates registering global, group, and route-level middlewares with custom IDs and priorities. The execution order is shown in the comments. ```go app.OnServe().BindFunc(func(se *core.ServeEvent) error { // attach global middleware se.Router.BindFunc(func(e *core.RequestEvent) error { println(0) return e.Next() }) g := se.Router.Group("/sub") // attach group middleware g.BindFunc(func(e *core.RequestEvent) error { println(1) return e.Next() }) // attach group middleware with an id and custom priority g.Bind(&hook.Handler[*core.RequestEvent]{ Id: "something", Func: func(e *core.RequestEvent) error { println(2) return e.Next() }, Priority: -1, }) // attach middleware to a single route // // "GET /sub/hello" should print the sequence: 2,0,1,3,4 g.GET("/hello", func(e *core.RequestEvent) error { println(4) return e.String(200, "Hello!") }).BindFunc(func(e *core.RequestEvent) error { println(3) return e.Next() }) return se.Next() }) ``` -------------------------------- ### Manual OAuth2 Authentication - Links Page Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt This section provides an HTML and JavaScript example for a web page that displays links to initiate OAuth2 authentication with various providers. It fetches available OAuth2 providers from the PocketBase API and constructs login URLs. ```APIDOC ## Manual OAuth2 Authentication - Links Page ### Description This web page displays links to initiate OAuth2 authentication with various providers. It fetches available OAuth2 providers from the PocketBase API and constructs login URLs. The provider's data is stored in local storage upon clicking a login link. ### Method Serves static HTML and executes client-side JavaScript. ### Endpoint (e.g. `https://127.0.0.1:8090/index.html`) ### Parameters None ### Request Example (See HTML/JavaScript code in source) ### Response Serves an HTML page with a list of login links. #### Success Response (200) HTML page with dynamically generated login links. #### Response Example (See HTML/JavaScript code in source) ### Error Handling Displays 'No OAuth2 providers.' if none are configured. ``` -------------------------------- ### Truncate Collection Dart Example Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example of how to truncate a collection (delete all its records) using the PocketBase Dart SDK. Requires authentication as a superuser. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); ... await pb.collection("_superusers").authWithPassword('test@example.com', '1234567890'); await pb.collections.truncate('demo'); ``` -------------------------------- ### Advanced Middleware Registration and Execution Order Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Demonstrates registering global middlewares with different priorities and attaching a middleware to a specific route. Shows the expected console log sequence. ```javascript // attach global middleware routerUse((e) => { console.log(1) return e.next() }) // attach global middleware with a custom priority routerUse(new Middleware((e) => { console.log(2) return e.next() }, -1)) // attach middleware to a single route // // "GET /hello" should print the sequence: 2,1,3,4 routerAdd("GET", "/hello", (e) => { console.log(4) return e.string(200, "Hello!") }, (e) => { console.log(3) return e.next() }) ``` -------------------------------- ### Truncate Collection JavaScript Example Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example of how to truncate a collection (delete all its records) using the PocketBase JavaScript SDK. Requires authentication as a superuser. ```javascript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); ... await pb.collection("_superusers").authWithPassword('test@example.com', '1234567890'); await pb.collections.truncate('demo'); ``` -------------------------------- ### Subscribe to Realtime Topic in JavaScript Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Listens for custom realtime messages on a specific topic. Initializes PocketBase and sets up a subscription to the 'example' topic, logging any received data. ```javascript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); ... await pb.realtime.subscribe('example', (e) => { console.log(e) }) ``` -------------------------------- ### Update Record Example in Dart Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example of how to update an existing record in a PocketBase collection using the Dart SDK. Ensure you have initialized the PocketBase client. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); ... final record = await pb.collection('demo').update('YOUR_RECORD_ID', body: { 'title': 'Lorem ipsum', }); ``` -------------------------------- ### Update Record Example in JavaScript Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example of how to update an existing record in a PocketBase collection using the JavaScript SDK. Ensure you have initialized the PocketBase client. ```javascript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); ... const record = await pb.collection('demo').update('YOUR_RECORD_ID', { title: 'Lorem ipsum', }); ``` -------------------------------- ### Serve Static Directory in Go Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Serves static files from a specified directory using an fs.FS instance. Expects a wildcard path parameter in the route. ```go app.OnServe().BindFunc(func(se *core.ServeEvent) error { // serves static files from the provided dir (if exists) se.Router.GET("/{path...}", apis.Static(os.DirFS("/path/to/public"), false)) return se.Next() }) ``` -------------------------------- ### Execute Raw SQL Query (SELECT All) Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Use All() to populate multiple rows into a slice of structs. The struct fields must match the selected columns and their database tags. ```go type User struct { Id string `db:"id" json:"id" Status bool `db:"status" json:"status" Age int `db:"age" json:"age" Roles types.JSONArray[string] `db:"roles" json:"roles" } users := []User{} err := app.DB(). NewQuery("SELECT id, status, age, roles FROM users LIMIT 100"). All(&users) ``` -------------------------------- ### Registering a GET route with a path parameter Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Registers a GET route that accepts a name parameter from the URL path. The handler returns a JSON response with a greeting message. ```javascript routerAdd("GET", "/hello/{name}", (e) => { let name = e.request.pathValue("name") return e.json(200, { "message": "Hello " + name }) }) ``` -------------------------------- ### OnTerminate Hook Example Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt The OnTerminate hook is triggered when the app is being terminated, for example, on a SIGTERM signal. Note that termination might be abrupt without awaiting hook completion. ```go package main import ( "log" "github.com/pocketbase/pocketbase" "github.com/pocketbase/pocketbase/core" ) func main() { app := pocketbase.New() app.OnTerminate().BindFunc(func(e *core.TerminateEvent) error { // e.App // e.IsRestart return e.Next() }) if err := app.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Create Initial Superuser Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt This snippet shows how to create an initial superuser record. It includes an optional revert operation to delete the superuser. Values can be loaded using environment variables or config files. ```javascript // pb_migrations/1687801090_initial_superuser.js migrate((app) => { let superusers = app.findCollectionByNameOrId("_superusers") let record = new Record(superusers) // note: the values can be eventually loaded via $os.getenv(key) // or from a special local config file record.set("email", "test@example.com") record.set("password", "1234567890") app.save(record) }, (app) => { // optional revert operation try { let record = app.findAuthRecordByEmail("_superusers", "test@example.com") app.delete(record) } catch { // silent errors (probably already deleted) } }) ``` -------------------------------- ### Registering a GET route with a named wildcard path parameter Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Matches any GET request that begins with the specified path prefix, capturing the rest of the path segments into a named parameter. ```javascript routerAdd("GET", "/static/{path...}", ...) ``` -------------------------------- ### Named Path Parameters Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Shows how to define and use named path parameters like `{name}` to capture dynamic parts of a URL, such as user identifiers. ```go // match "GET /customers/john", "GET /customer/jane", etc. se.Router.GET("/customers/{name}") ``` -------------------------------- ### Initialize Default Application Settings Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt This snippet demonstrates how to set default application settings, including metadata like app name and URL, and logging configurations. Changes are saved using app.save(settings). ```javascript // pb_migrations/1687801090_initial_settings.js migrate((app) => { let settings = app.settings() // for all available settings fields you could check // /jsvm/interfaces/core.Settings.html settings.meta.appName = "test" settings.meta.appURL = "https://example.com" settings.logs.maxDays = 2 settings.logs.logAuthId = true settings.logs.logIP = false app.save(settings) }) ``` -------------------------------- ### Connect to Realtime API Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Establishes a new SSE connection to the Realtime API. A PB_CONNECT SSE event is immediately sent with the client ID. User authorization is handled during the first subscription request. ```APIDOC ## GET /api/realtime ### Description Establishes a new SSE connection and immediately sends a `PB_CONNECT` SSE event with the created client ID. The user/superuser authorization happens during the first Set subscriptions call. ### Method GET ### Endpoint /api/realtime ``` -------------------------------- ### Example Usage of @now Macro Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Compares the publicDate field with the current datetime. ```plaintext @request.body.publicDate >= @now ``` -------------------------------- ### Ownership-Based Access Control Rule Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example rule to grant access to a record only to its author. ```plaintext @request.auth.id != "" && author = @request.auth.id ``` -------------------------------- ### Create View Collection in JavaScript Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Demonstrates creating a 'view' collection with a custom SQL query to define its schema and data using the PocketBase JavaScript SDK. Requires superuser authentication. ```javascript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); ... await pb.collection("_superusers").authWithPassword('test@example.com', '1234567890'); // create view collection const view = await pb.collections.create({ name: 'exampleView', type: 'view', listRule: '@request.auth.id != ""', viewRule: null, // the schema will be autogenerated from the below query viewQuery: 'SELECT id, name from posts', }); ``` -------------------------------- ### Build PocketBase Docker Image Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Commands to download, unzip, and configure PocketBase within a Docker image. Ensure to uncomment COPY lines if local migrations or hooks are needed. ```docker ADD https://github.com/pocketbase/pocketbase/releases/download/v${PB_VERSION}/pocketbase_${PB_VERSION}_linux_amd64.zip /tmp/pb.zip RUN unzip /tmp/pb.zip -d /pb/ # uncomment to copy the local pb_migrations dir into the image # COPY ./pb_migrations /pb/pb_migrations # uncomment to copy the local pb_hooks dir into the image # COPY ./pb_hooks /pb/pb_hooks EXPOSE 8080 # start PocketBase CMD ["/pb/pocketbase", "serve", "--http=0.0.0.0:8080"] ``` -------------------------------- ### Filtering by HTTP Request Method Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example of filtering records based on the HTTP request method. ```plaintext @request.method = "GET" ``` -------------------------------- ### GET /api/logs/stats Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Retrieves statistics about the logs. Requires an Authorization token. Supports filtering and field selection. ```APIDOC ## GET /api/logs/stats ### Description Retrieves statistics about the logs. This endpoint requires an `Authorization: TOKEN` header for authentication. It supports filtering logs based on various criteria and selecting specific fields to be returned in the response. ### Method GET ### Endpoint /api/logs/stats ### Parameters #### Query Parameters - **filter** (String) - Optional - Filter expression to filter/search the logs. Example: `?filter=(data.url~'test.com' && level>0)`. Supported log filter fields include `rowid`, `id`, `created`, `updated`, `level`, `message`, and any `data.*` attribute. The syntax follows `OPERAND OPERATOR OPERAND` with various operators like `=`, `!=`, `>`, `>=`, `<`, `<=`, `~`, `!~`, `?=`, `?!=`, `?>`, `?>=`, `?<`, `?<=`, `?~`, `?!~`. Parentheses `()`, `&&`, and `||` can be used for grouping, and single line comments `//` are supported. - **fields** (String) - Optional - Comma-separated string of the fields to return in the JSON response. Defaults to all fields. Example: `?fields=*,expand.relField.name`. `*` targets all keys at the current depth. The `:excerpt(maxLength, withEllipsis?)` modifier can be used to return a short plain text version of a string field. ### Request Example (No request body example provided in source) ### Response #### Success Response (200) An array of objects, where each object contains a `total` count and a `date`. Example: [ { "total": 4, "date": "2022-06-01 19:00:00.000" }, { "total": 1, "date": "2022-06-02 12:00:00.000" }, { "total": 8, "date": "2022-06-02 13:00:00.000" } ] #### Error Responses - **400 Bad Request**: Indicates an issue with the request processing, such as an invalid filter. Example: { "status": 400, "message": "Something went wrong while processing your request. Invalid filter.", "data": {} } - **401 Unauthorized**: Returned when the request lacks a valid authorization token. Example: { "status": 401, "message": "The request requires valid record authorization token.", "data": {} } - **403 Forbidden**: Returned when the authorized record is not permitted to perform the requested action. Example: { "status": 403, "message": "The authorized record is not allowed to perform this action.", "data": {} } ``` -------------------------------- ### Serving a Single File Response in Go Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Serve a single file from a filesystem with the response. ```go e.FileFS(os.DirFS("..."), "example.txt") ``` -------------------------------- ### Filtering by Request Query Parameters Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example of filtering records based on query parameters in the request URL. ```plaintext @request.query.page = "1" ``` -------------------------------- ### Go: Listen to Collection Creation Events Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Bind functions to listen for collection creation events. Can be configured to fire for all collections or specific named collections. ```go package main import ( "log" "github.com/pocketbase/pocketbase" "github.com/pocketbase/pocketbase/core" ) func main() { app := pocketbase.New() // fires for every collection app.OnCollectionCreateExecute().BindFunc(func(e *core.CollectionEvent) error { // e.App // e.Collection return e.Next() }) // fires only for "users" and "articles" collections app.OnCollectionCreateExecute("users", "articles").BindFunc(func(e *core.CollectionEvent) error { // e.App // e.Collection return e.Next() }) if err := app.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Batch Request Forbidden Response Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example of a 403 Forbidden response, indicating that batch requests are not allowed. ```json { "status": 403, "message": "Batch requests are not allowed.", "data": {} } ``` -------------------------------- ### Create raw SQL expressions with parameters Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Use dbx.NewExp() to create expressions with raw SQL fragments and bind parameters using dbx.Params for safety. ```Go dbx.NewExp("status = 'public'") dbx.NewExp("total > {:min} AND total < {:max}", dbx.Params{ "min": 10, "max": 30 }) ``` -------------------------------- ### Mixed Access Control Rule Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example rule combining role and ownership checks for access control. ```plaintext @request.auth.id != "" && (@request.auth.role = "staff" || author = @request.auth.id) ``` -------------------------------- ### List Application Settings (JavaScript) Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Fetches all application settings. Requires superuser authentication. Secret fields are redacted. ```javascript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); ... await pb.collection("_superusers").authWithPassword('test@example.com', '1234567890'); const settings = await pb.settings.getAll(); ``` -------------------------------- ### Get a Single Log Entry (Dart) Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Retrieves a single log entry by its ID. Requires authentication as a superuser. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); ... await pb.collection("_superusers").authWithEmail('test@example.com', '123456'); final log = await pb.logs.getOne('LOG_ID'); ``` -------------------------------- ### Get a Single Log Entry (JavaScript) Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Retrieves a single log entry by its ID. Requires authentication as a superuser. ```javascript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); ... await pb.collection("_superusers").authWithEmail('test@example.com', '123456'); const log = await pb.logs.getOne('LOG_ID'); ``` -------------------------------- ### Example Base Collection Schema Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Defines the schema for a 'posts' collection with an auto-generated ID, title, and creation/update timestamps. ```json { "id": "_pbc_2287844090", "listRule": null, "viewRule": null, "createRule": null, "updateRule": null, "deleteRule": null, "name": "posts", "type": "base", "fields": [ { "autogeneratePattern": "[a-z0-9]{15}", "hidden": false, "id": "text3208210256", "max": 15, "min": 15, "name": "id", "pattern": "^[a-z0-9]+$", "presentable": false, "primaryKey": true, "required": true, "system": true, "type": "text" }, { "autogeneratePattern": "", "hidden": false, "id": "text724990059", "max": 0, "min": 0, "name": "title", "pattern": "", "presentable": false, "primaryKey": false, "required": false, "system": false, "type": "text" }, { "hidden": false, "id": "autodate2990389176", "name": "created", "onCreate": true, "onUpdate": false, "presentable": false, "system": false, "type": "autodate" }, { "hidden": false, "id": "autodate3332085495", "name": "updated", "onCreate": true, "onUpdate": true, "presentable": false, "system": false, "type": "autodate" } ], "indexes": [], "system": false } ``` -------------------------------- ### Nested Relation Access Control Rule Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Example rule demonstrating access control through nested relation fields. ```plaintext someRelField.anotherRelField.author = @request.auth.id ``` -------------------------------- ### Register Global Middleware Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Shows how to register a global middleware function that intercepts requests. This example checks for a missing 'Something' header and returns a bad request error if not found. ```go app.OnServe().BindFunc(func(se *core.ServeEvent) error { // register a global middleware se.Router.BindFunc(func(e *core.RequestEvent) error { if e.Request.Header.Get("Something") == "" { return e.BadRequestError("Something header value is missing!", nil) } return e.Next() }) return se.Next() }) ``` -------------------------------- ### Get Log Statistics (Dart) Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Retrieves hourly aggregated log statistics. Requires authentication as a superuser. Supports filtering. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); ... await pb.collection("_superusers").authWithPassword('test@example.com', '123456'); final stats = await pb.logs.getStats( filter: 'data.status >= 400' ); ``` -------------------------------- ### Register Custom Console Command in Go Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Use app.RootCmd.AddCommand() to register custom console commands. This example adds a 'hello' command that prints 'Hello world!'. ```go app.RootCmd.AddCommand(&cobra.Command{ Use: "hello", Run: func(cmd *cobra.Command, args []string) { print("Hello world!") }, }) ``` -------------------------------- ### Get Log Statistics (JavaScript) Source: https://raw.githubusercontent.com/Suryapratap-R/pocketbase-llm-txt/refs/heads/main/llms-full.txt Retrieves hourly aggregated log statistics. Requires authentication as a superuser. Supports filtering. ```javascript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); ... await pb.collection("_superusers").authWithPassword('test@example.com', '123456'); const stats = await pb.logs.getStats({ filter: 'data.status >= 400' }); ```