### PocketBase Go Application Setup Source: https://pocketbase.io/old/docs/go-overview Example of a basic PocketBase application written in Go. It initializes the PocketBase app and sets up a handler for serving static files from the './pb_public' directory. ```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() // serves static files from the provided public dir (if exists) app.OnBeforeServe().Add(func(e *core.ServeEvent) error { e.Router.GET("/*", apis.StaticDirectoryHandler(os.DirFS("./pb_public"), false)) return nil }) if err := app.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### PocketBase Dockerfile Example Source: https://pocketbase.io/old/docs/going-to-production A sample Dockerfile for deploying PocketBase. It downloads a specific version, installs dependencies, and sets the command to run the PocketBase server. ```dockerfile FROM alpine:latest ARG PB_VERSION=0.22.34 RUN apk add --no-cache \ unzip \ ca-certificates # download and unzip PocketBase 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 ["/old/pb/pocketbase", "serve", "--http=0.0.0.0:8080"] ``` -------------------------------- ### PocketBase Serve Command Example Source: https://pocketbase.io/old/docs/going-to-production Demonstrates how to start the PocketBase executable for production, including auto-managed TLS with Let's Encrypt. It shows the command to run the server with a domain name. ```Shell [root@dev ~]$ /root/pb/pocketbase serve yourdomain.com ``` -------------------------------- ### Start PocketBase Server Source: https://pocketbase.io/old/docs/index Instructions on how to start the PocketBase server application after extracting the downloaded archive. This command initiates the embedded server. ```Shell ./pocketbase serve ``` -------------------------------- ### Systemd Service File for PocketBase Source: https://pocketbase.io/old/docs/going-to-production An example Systemd service file configuration for PocketBase, allowing it to start automatically and restart on failure. It specifies logging and execution parameters. ```Shell [Unit] Description = pocketbase [Service] Type = simple User = root Group = root LimitNOFILE = 4096 Restart = always RestartSec = 5s StandardOutput = append:/root/pb/errors.log StandardError = append:/root/pb/errors.log ExecStart = /root/pb/pocketbase serve yourdomain.com [Install] WantedBy = multi-user.target ``` -------------------------------- ### Go: Setup Custom API Route with Admin Auth Source: https://pocketbase.io/old/docs/go-testing Example demonstrating how to define a custom API route in PocketBase using Go. It includes setting up the route, handling requests, and applying admin authentication middleware. ```Go // main.go package main import ( "log" "net/http" "github.com/labstack/echo/v5" "github.com/pocketbase/pocketbase" "github.com/pocketbase/pocketbase/apis" "github.com/pocketbase/pocketbase/core" ) func bindAppHooks(app core.App) { app.OnBeforeServe().Add(func(e *core.ServeEvent) error { e.Router.AddRoute(echo.Route{ Method: http.MethodGet, Path: "/old/my/hello", Handler: func(c echo.Context) error { return c.String(200, "Hello world!") }, Middlewares: []echo.MiddlewareFunc{ apis.RequireAdminAuth(), }, }) return nil }) } func main() { app := pocketbase.New() bindAppHooks(app) if err := app.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Systemd Service Management Commands Source: https://pocketbase.io/old/docs/going-to-production Commands to enable and start the PocketBase service using `systemctl` after creating the service file. ```Shell [root@dev ~]$ systemctl enable pocketbase.service [root@dev ~]$ systemctl start pocketbase ``` -------------------------------- ### Go Logging Examples Source: https://pocketbase.io/old/docs/go-logging Illustrative examples of using the PocketBase Go logger methods to log messages with and without attributes. ```go app.Logger().Debug("Debug message!") app.Logger().Debug( "Debug message with attributes!", "name", "John Doe", "id", 123, ) ``` ```go app.Logger().Info("Info message!") app.Logger().Info( "Info message with attributes!", "name", "John Doe", "id", 123, ) ``` ```go app.Logger().Warn("Warning message!") app.Logger().Warn( "Warning message with attributes!", "name", "John Doe", "id", 123, ) ``` ```go app.Logger().Error("Error message!") app.Logger().Error( "Error message with attributes!", "id", 123, "error", err, ) ``` ```go l := app.Logger().With("total", 123) l.Info("message A") l.Info("message B", "name", "john") ``` ```go l := app.Logger().WithGroup("sub") l.Info("message A", "total", 123) ``` -------------------------------- ### Create Backup SDK Examples Source: https://pocketbase.io/old/docs/api-backups Illustrates how to trigger a new backup creation using PocketBase SDKs for JavaScript and Dart. Admin authentication is a prerequisite. ```javascript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); ... await pb.admins.authWithPassword('test@example.com', '1234567890'); await pb.backups.create('new_backup.zip'); ``` ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); ... await pb.admins.authWithPassword('test@example.com', '1234567890'); await pb.backups.create('new_backup.zip'); ``` -------------------------------- ### PocketBase Go Extension Overview Source: https://pocketbase.io/old/docs/client-side-sdks Guides for extending PocketBase functionality using the Go programming language. Covers core concepts and specific features. ```APIDOC Go Extension: Overview: General guide to extending PocketBase with Go. Event hooks: Handling application events. Routing: Customizing API routes. Database: Interacting with the database. Record operations: Managing collection records. Collection operations: Managing collections. Migrations: Database schema changes. Jobs scheduling: Background task execution. Console commands: Custom CLI commands. Sending emails: Email integration. Rendering templates: Server-side template rendering. Logging: Application logging. Testing: Writing tests for Go extensions. Custom models: Defining custom data models. ``` -------------------------------- ### List Backups SDK Examples Source: https://pocketbase.io/old/docs/api-backups Demonstrates how to fetch the list of backups using PocketBase SDKs for JavaScript and Dart. Requires admin authentication. ```javascript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); ... await pb.admins.authWithPassword('test@example.com', '1234567890'); const backups = await pb.backups.getFullList(); ``` ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); ... await pb.admins.authWithPassword('test@example.com', '1234567890'); final backups = await pb.backups.getFullList(); ``` -------------------------------- ### Start PocketBase Server with Encryption Enabled Source: https://pocketbase.io/old/docs/going-to-production Starts the PocketBase server application, instructing it to use the environment variable specified by `--encryptionEnv` to encrypt application settings stored in the database. Ensure the environment variable is set before running this command. ```shell pocketbase serve --encryptionEnv=PB_ENCRYPTION_KEY ``` -------------------------------- ### PocketBase Dart SDK Initialization and Admin Auth Source: https://pocketbase.io/old/docs/api-collections Demonstrates how to initialize the PocketBase client and authenticate as an admin using email and password. This is a common starting point for server-side operations. ```dart import 'package:pocketbase/pocketbase.dart'; // Initialize PocketBase client final pb = PocketBase('http://127.0.0.1:8090'); // Authenticate as admin // Replace with actual admin credentials await pb.admins.authWithPassword('test@example.com', '123456'); // Example of updating a collection (demonstrated in another snippet) // final collection = await pb.collections.update('demo', body: { // 'name': 'new_demo', // 'listRule': 'created > "2022-01-01 00:00:00"', // }); ``` -------------------------------- ### Create Single Record Snippets Source: https://pocketbase.io/old/docs/api-records Examples demonstrating how to create a new record in a collection using PocketBase SDKs. ```JavaScript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); ... const record = await pb.collection('demo').create({ title: 'Lorem ipsum', }); ``` ```Dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); ... final record = await pb.collection('demo').create(body: { 'title': 'Lorem ipsum', }); ``` -------------------------------- ### Writing Response Body Source: https://pocketbase.io/old/docs/js-routing Provides examples for sending various types of responses, including JSON, plain strings, HTML, redirects, and responses with no content. ```javascript // send response with json body c.json(200, {"name": "John"}) ``` ```javascript // send response with string body c.string(200, "Lorem ipsum...") ``` ```javascript // send response with html body // (check also the "Rendering templates" section) c.html(200, "

Hello!

") ``` ```javascript // redirect c.redirect(307, "https://example.com") ``` ```javascript // send response with no body c.noContent(204) ``` -------------------------------- ### Running Custom Go Console Commands Source: https://pocketbase.io/old/docs/go-console-commands Shows the command-line execution for a custom Go console command registered with PocketBase. This example assumes the application is built into an executable named `myapp`. ```Shell # or "go run main.go hello" ./myapp hello ``` -------------------------------- ### PocketBase JavaScript Extension Overview Source: https://pocketbase.io/old/docs/client-side-sdks Guides for extending PocketBase functionality using JavaScript, typically within the JSVM (JavaScript Virtual Machine) environment. ```APIDOC JavaScript Extension: Overview: General guide to extending PocketBase with JavaScript. Event hooks: Handling application events. Routing: Customizing API routes. Database: Interacting with the database. Record operations: Managing collection records. Collection operations: Managing collections. Migrations: Database schema changes. Jobs scheduling: Background task execution. Console commands: Custom CLI commands. Sending emails: Email integration. Sending HTTP requests: Making external HTTP calls. Rendering templates: Server-side template rendering. Logging: Application logging. Types reference: Reference for available JavaScript types and APIs. ``` -------------------------------- ### Create Admin (JavaScript) Source: https://pocketbase.io/old/docs/api-admins Example of creating a new admin user using the PocketBase JavaScript SDK. This involves initializing the client and calling the `admins.create` method with the necessary credentials and user details. ```javascript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); // Authenticate an existing admin to perform the creation await pb.admins.authWithPassword('test@example.com', '1234567890'); // Create a new admin const admin = await pb.admins.create({ email: 'new@example.com', password: '1234567890', passwordConfirm: '1234567890', avatar: 8, }); ``` -------------------------------- ### Create Admin (Dart) Source: https://pocketbase.io/old/docs/api-admins Example of creating a new admin user using the PocketBase Dart SDK. This involves initializing the client and calling the `admins.create` method with the necessary credentials and user details. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); // Authenticate an existing admin to perform the creation await pb.admins.authWithPassword('test@example.com', '1234567890'); // Create a new admin final admin = await pb.admins.create(body: { 'email': 'new@example.com', 'password': '1234567890', 'passwordConfirm': '1234567890', 'avatar': 8, }); ``` -------------------------------- ### Caddy Proxy Configuration Source: https://pocketbase.io/old/docs/going-to-production Example Caddy configuration for proxying requests to a PocketBase backend. It includes request body size limits and transport read timeouts. ```caddy example.com { request_body { max_size 10MB } reverse_proxy 127.0.0.1:8090 { transport http { read_timeout 360s } } } ``` -------------------------------- ### PocketBase Admin API Documentation Source: https://pocketbase.io/old/docs/api-admins Details for interacting with the PocketBase Admin API endpoints for creating and updating administrators. Includes request methods, paths, parameters, and response examples. ```apidoc POST /api/admins Creates a new admin. Requires `Authorization: TOKEN` header. Body Parameters: - Optional id (String): 15 characters string to store as admin ID. Auto-generated if not set. - Required email (String): Admin email address. - Required password (String): Admin password. - Required passwordConfirm (String): Admin password confirmation. - Optional avatar (Number): Admin avatar image key (0-9). Body can be sent as JSON or multipart/form-data. Query Parameters: - fields (String): Comma separated string of fields to return in the JSON response. Supports modifiers like `:excerpt(maxLength, withEllipsis?)`. Responses: - 200 OK: Returns the created admin object. Example: { "id": "b6e4b08274f34e9", "created": "2022-06-22 07:13:09.735Z", "updated": "2022-06-22 07:15:09.735Z", "email": "new@example.com", "avatar": 8 } - 400 Bad Request: An error occurred during form submission (e.g., validation errors). Example: { "code": 400, "message": "An error occurred while submitting the form.", "data": { "email": { "code": "validation_required", "message": "Missing required value." } } } - 401 Unauthorized: Request requires admin authorization token. - 403 Forbidden: User is not allowed to perform this request. PATCH /api/admins/{id} Updates a single admin model by its ID. Requires `Authorization: TOKEN` header. Path Parameters: - id (String): ID of the admin to update. Body Parameters: - Optional email (String): New admin email address. - Optional password (String): New admin password. - Optional passwordConfirm (String): New admin password confirmation. - Optional avatar (Number): New admin avatar key (0-9). Body can be sent as JSON or multipart/form-data. Query Parameters: - fields (String): Comma separated string of fields to return in the JSON response. Supports modifiers like `:excerpt(maxLength, withEllipsis?)`. Responses: - 200 OK: Returns the updated admin object. Example: { "id": "b6e4b08274f34e9", "created": "2022-06-22 07:13:09.735Z", "updated": "2022-06-22 07:15:09.735Z", "email": "test@example.com", "avatar": 4 } - 400 Bad Request: An error occurred during form submission (e.g., validation errors). Example: { "code": 400, "message": "An error occurred while submitting the form.", "data": { "email": { "code": "validation_invalid_email", "message": "Invalid email value." } } } - 401 Unauthorized: Request requires admin authorization token. - 403 Forbidden: User is not allowed to perform this request. - 404 Not Found: The requested admin resource was not found. ``` -------------------------------- ### Get Single Record Snippets Source: https://pocketbase.io/old/docs/api-records Examples demonstrating how to fetch a single record from a collection using PocketBase SDKs. ```JavaScript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); ... const record1 = await pb.collection('posts').getOne('RECORD_ID', { expand: 'relField1,relField2.subRelField', }); ``` ```Dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); ... final record1 = await pb.collection('posts').getOne('RECORD_ID', expand: 'relField1,relField2.subRelField', ); ``` -------------------------------- ### Go SDK Overview Link Source: https://pocketbase.io/old/docs/going-to-production Link to the Go SDK overview documentation for extending PocketBase with Go. ```Go [Go Overview](/old/docs/go-overview) ``` -------------------------------- ### PocketBase Go SDK Overview Source: https://pocketbase.io/old/docs/api-records Guides for extending PocketBase with Go, covering core concepts, event hooks, routing, database operations, record and collection management, migrations, job scheduling, console commands, email sending, template rendering, logging, testing, and custom models. ```Go Go Overview: - Introduction to using Go with PocketBase. Go Event hooks: - Registering and managing server-side event hooks. Go Routing: - Defining custom API routes in Go. Go Database: - Interacting with the PocketBase database. Go Record operations: - Performing CRUD operations on records using the Go SDK. Go Collection operations: - Managing collections via the Go SDK. Go Migrations: - Implementing database migrations in Go. Go Jobs scheduling: - Scheduling background jobs with Go. Go Console commands: - Creating custom CLI commands for PocketBase. Go Sending emails: - Sending emails from your Go application. Go Rendering templates: - Rendering templates within PocketBase Go applications. Go Logging: - Implementing logging in Go extensions. Go Testing: - Writing tests for Go PocketBase extensions. Go Custom models: - Defining custom Go models for your data. ``` -------------------------------- ### Go SDK Overview Source: https://pocketbase.io/old/docs/index Provides an entry point to the Go SDK documentation for extending PocketBase. Covers topics like event hooks, routing, database operations, and custom models. ```Go // See /old/docs/go-overview for full details // Example: Initializing the Go SDK // import "github.com/pocketbase/pocketbase" // pb := pocketbase.New() // Available Go topics: // - Event hooks (/old/docs/go-event-hooks) // - Routing (/old/docs/go-routing) // - Database operations (/old/docs/go-database) // - Record operations (/old/docs/go-records) // - Collection operations (/old/docs/go-collections) // - Migrations (/old/docs/go-migrations) // - Jobs scheduling (/old/docs/go-jobs-scheduling) // - Console commands (/old/docs/go-console-commands) // - Sending emails (/old/docs/go-sending-emails) // - Rendering templates (/old/docs/go-rendering-templates) // - Logging (/old/docs/go-logging) // - Testing (/old/docs/go-testing) // - Custom models (/old/docs/go-custom-models) ``` -------------------------------- ### PocketBase JavaScript Custom Route with Template Rendering Source: https://pocketbase.io/old/docs/js-rendering-templates Illustrates how to register a custom GET route in PocketBase using the `routerAdd` function. This example shows how to capture path parameters, load and render HTML templates using the `$template` helper, and return the rendered HTML response. ```javascript routerAdd("get", "/hello/:name", (c) => { const name = c.pathParam("name") const html = $template.loadFiles( `${__hooks}/views/layout.html`, `${__hooks}/views/hello.html`, ).render({ "name": name, }) return c.html(200, html) }) ``` -------------------------------- ### PocketBase JavaScript SDK Overview Source: https://pocketbase.io/old/docs/api-records Guides for using PocketBase with JavaScript, covering core concepts, event hooks, routing, database operations, record and collection management, migrations, job scheduling, console commands, email sending, HTTP requests, template rendering, and logging. ```JavaScript JS Overview: - Introduction to using JavaScript with PocketBase. JS Event hooks: - Registering and managing server-side event hooks. JS Routing: - Defining custom API routes in JavaScript. JS Database: - Interacting with the PocketBase database. JS Record operations: - Performing CRUD operations on records using the JS SDK. JS Collection operations: - Managing collections via the JS SDK. JS Migrations: - Implementing database migrations in JavaScript. JS Jobs scheduling: - Scheduling background jobs with JavaScript. JS Console commands: - Creating custom CLI commands for PocketBase. JS Sending emails: - Sending emails from your JavaScript application. JS Sending HTTP requests: - Making HTTP requests from the JS SDK. JS Rendering templates: - Rendering templates within PocketBase JS applications. JS Logging: - Implementing logging in JS extensions. JS Types reference: - Reference for JavaScript types used in PocketBase. ``` -------------------------------- ### Query Builder: Basic SELECT, FROM, WHERE, LIMIT, ORDER BY Source: https://pocketbase.io/old/docs/go-database Demonstrates the core components of the PocketBase Go SDK's query builder for constructing a SELECT statement. It shows how to specify columns, tables, filtering conditions, result limits, and ordering. ```go users := []struct { Id string `db:"id" json:"id"` Email string `db:"email" json:"email"` }{} app.Dao().DB(). Select("id", "email"). From("users"). AndWhere(dbx.Like("email", "example.com")). Limit(100). OrderBy("created ASC"). All(&users) ``` -------------------------------- ### View Collection SQL Query Example Source: https://pocketbase.io/old/docs/collections Example SQL query to create a read-only view collection that aggregates data from other collections. This demonstrates how to populate view collections with custom queries, including aggregations. ```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 ``` -------------------------------- ### PocketBase Use as Framework Source: https://pocketbase.io/old/docs/client-side-sdks Instructions on leveraging PocketBase as a backend-as-a-service (BaaS) or a standalone backend framework. ```APIDOC Use as Framework: Core Concepts: - PocketBase provides a built-in Go server that can be extended. - Define custom routes, handlers, and business logic in Go. - Utilize PocketBase's database, auth, and file storage capabilities. Extensibility: - Go plugins: Add custom functionality directly into the server binary. - JSVM: Run JavaScript code for server-side logic. Deployment: - Compile PocketBase with your custom Go code into a single binary. - Deploy this binary as your application's backend. ``` -------------------------------- ### PocketBase Access Rule Examples Source: https://pocketbase.io/old/docs/api-rules-and-filters These examples demonstrate common access control rules in PocketBase. They cover scenarios like allowing only registered users, filtering records based on status or related data, and restricting access based on field content patterns. ```PocketBase Rules // Allow only registered users: @request.auth.id != "" ``` ```PocketBase Rules // Allow only registered users and return records that are either "active" or "pending": @request.auth.id != "" && (status = "active" || status = "pending") ``` ```PocketBase Rules // Allow only registered users who are listed in an *allowed_users* multi-relation field value: @request.auth.id != "" && allowed_users.id ?= @request.auth.id ``` ```PocketBase Rules // Allow access by anyone and return only the records where the *title* field value starts with "Lorem" (ex. "Lorem ipsum"): title ~ "Lorem%" ``` -------------------------------- ### JS SDK Overview Link Source: https://pocketbase.io/old/docs/going-to-production Link to the JavaScript SDK overview documentation for extending PocketBase with JavaScript. ```JavaScript [JS Overview](/old/docs/js-overview) ``` -------------------------------- ### Delete Collection Example (Dart) Source: https://pocketbase.io/old/docs/api-collections Demonstrates how to delete a PocketBase collection using the Dart SDK. Requires admin authentication. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); // Authenticate as admin await pb.admins.authWithPassword('test@example.com', '1234567890'); // Delete a collection by its ID or name await pb.collections.delete('demo'); ``` -------------------------------- ### Go: Render HTML Templates with PocketBase Utility Source: https://pocketbase.io/old/docs/go-rendering-templates Demonstrates how to render HTML templates using PocketBase's utility package, which wraps the Go standard library's `html/template`. It shows loading multiple files and passing data for rendering, with built-in auto-escaping for security. ```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 Example (JavaScript) Source: https://pocketbase.io/old/docs/api-collections Demonstrates how to delete a PocketBase collection using the JavaScript SDK. Requires admin authentication. ```javascript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); // Authenticate as admin await pb.admins.authWithPassword('test@example.com', '1234567890'); // Delete a collection by its ID or name await pb.collections.delete('demo'); ``` -------------------------------- ### Delete Record Source: https://pocketbase.io/old/docs/js-records Provides a simple example of how to delete a record from a collection in PocketBase by first retrieving the record and then calling the delete method. ```javascript const record = $app.dao().findRecordById("articles", "RECORD_ID") $app.dao().deleteRecord(record) ``` -------------------------------- ### JavaScript SDK Overview Source: https://pocketbase.io/old/docs/index Provides an entry point to the JavaScript SDK documentation for extending PocketBase. Covers topics like event hooks, routing, database operations, and sending HTTP requests. ```JavaScript // See /old/docs/js-overview for full details // Example: Initializing the JS SDK // import PocketBase from 'pocketbase' // const pb = new PocketBase('YOUR_PB_URL'); // Available JS topics: // - Event hooks (/old/docs/js-event-hooks) // - Routing (/old/docs/js-routing) // - Database operations (/old/docs/js-database) // - Record operations (/old/docs/js-records) // - Collection operations (/old/docs/js-collections) // - Migrations (/old/docs/js-migrations) // - Jobs scheduling (/old/docs/js-jobs-scheduling) // - Console commands (/old/docs/js-console-commands) // - Sending emails (/old/docs/js-sending-emails) // - Sending HTTP requests (/old/docs/js-sending-http-requests) // - Rendering templates (/old/docs/js-rendering-templates) // - Logging (/old/docs/js-logging) // - Types reference (/old/jsvm/index.html) ``` -------------------------------- ### JavaScript App Hooks: onTerminate Source: https://pocketbase.io/old/docs/js-event-hooks The onTerminate hook is triggered when the application is in the process of shutting down, for example, upon receiving a SIGTERM signal. ```javascript onTerminate((e) => { console.log("terminating...") }) ``` -------------------------------- ### Response Structure with Expanded User Source: https://pocketbase.io/old/docs/working-with-relations Example JSON response when expanding the 'user' relation for comments. The 'expand' object contains the nested user data. ```json { "page": 1, "perPage": 30, "totalPages": 1, "totalItems": 20, "items": [ { "id": "lmPJt4Z9CkLW36z", "collectionId": "BHKW36mJl3ZPt6z", "collectionName": "comments", "created": "2022-01-01 01:00:00.456Z", "updated": "2022-01-01 02:15:00.456Z", "post": "WyAw4bDrvws6gGl", "user": "FtHAW9feB5rze7D", "message": "Example message...", "expand": { "user": { "id": "FtHAW9feB5rze7D", "collectionId": "srmAo0hLxEqYF7F", "collectionName": "users", "created": "2022-01-01 00:00:00.000Z", "updated": "2022-01-01 00:00:00.000Z", "username": "users54126", "verified": false, "emailVisibility": false, "name": "John Doe" } } }, ... ] } ``` -------------------------------- ### PocketBase Going to Production Source: https://pocketbase.io/old/docs/client-side-sdks Best practices and considerations for deploying PocketBase applications to production environments. ```APIDOC Going to Production: Deployment: - Compile PocketBase with custom Go code into a single binary. - Use a process manager (e.g., systemd, PM2) to keep the server running. - Deploy behind a reverse proxy (e.g., Nginx, Caddy) for SSL termination and load balancing. Security: - Use HTTPS. - Secure your admin panel credentials. - Implement robust collection rules and API filters. Database: - Regularly back up your PocketBase data file. - Consider using a managed database solution if self-hosting is not preferred. Performance: - Optimize queries and collection rules. - Cache frequently accessed data where appropriate. ``` -------------------------------- ### PocketBase Go Server with HTML Templating Source: https://pocketbase.io/old/docs/go-rendering-templates A Go program using the PocketBase SDK to set up a web server. It registers a custom route that renders HTML pages by combining a layout and a specific template with dynamic data. ```go package main import ( "log" "net/http" "github.com/labstack/echo/v5" "github.com/pocketbase/pocketbase" "github.com/pocketbase/pocketbase/apis" "github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/tools/template" ) func main() { app := pocketbase.New() // Add an event listener for the OnBeforeServe event app.OnBeforeServe().Add(func(e *core.ServeEvent) error { // Initialize a template registry to manage parsed templates // This registry is safe to be used by multiple goroutines registry := template.NewRegistry() // Register a GET route for /old/hello/:name e.Router.GET("/old/hello/:name", func(c echo.Context) error { // Extract the 'name' path parameter name := c.PathParam("name") // Load and render HTML files using the template registry // This combines 'views/layout.html' and 'views/hello.html' html, err := registry.LoadFiles( "views/layout.html", "views/hello.html", ).Render(map[string]any{ "name": name, }) if err != nil { // Return a 404 Not Found error if rendering fails return apis.NewNotFoundError("", err) } // Respond with the rendered HTML return c.HTML(http.StatusOK, html) }) return nil }) // Start the PocketBase server if err := app.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Response Structure with Expanded Back-Relations Source: https://pocketbase.io/old/docs/working-with-relations Example JSON response when filtering and expanding back-relations. The 'expand' object shows an array of comments, each with its expanded user data. ```json { "page": 1, "perPage": 30, "totalPages": 2, "totalItems": 45, "items": [ { "id": "WyAw4bDrvws6gGl", "collectionId": "1rAwHJatkTNCUIN", "collectionName": "posts", "created": "2022-01-01 01:00:00.456Z", "updated": "2022-01-01 02:15:00.456Z", "title": "Lorem ipsum dolor sit...", "expand": { "comments_via_post": [ { "id": "lmPJt4Z9CkLW36z", "collectionId": "BHKW36mJl3ZPt6z", "collectionName": "comments", "created": "2022-01-01 01:00:00.456Z", "updated": "2022-01-01 02:15:00.456Z", "post": "WyAw4bDrvws6gGl", "user": "FtHAW9feB5rze7D", "message": "lorem ipsum...", "expand": { "user": { "id": "FtHAW9feB5rze7D", "collectionId": "srmAo0hLxEqYF7F", "collectionName": "users", "created": "2022-01-01 00:00:00.000Z", "updated": "2022-01-01 00:00:00.000Z", "username": "users54126", "verified": false, "emailVisibility": false, "name": "John Doe" } } }, { "id": "tu4Z9CkLW36mPJz", "collectionId": "BHKW36mJl3ZPt6z", "collectionName": "comments", "created": "2022-01-01 01:10:00.123Z", "updated": "2022-01-01 02:39:00.456Z", "post": "WyAw4bDrvws6gGl", "user": "FtHAW9feB5rze7D", "message": "hello...", "expand": { "user": { "id": "FtHAW9feB5rze7D", "collectionId": "srmAo0hLxEqYF7F", "collectionName": "users", "created": "2022-01-01 00:00:00.000Z", "updated": "2022-01-01 00:00:00.000Z", "username": "users54126", "verified": false, "emailVisibility": false, "name": "John Doe" } } }, ... ] } }, ... ] } ``` -------------------------------- ### Delete Record (Go) Source: https://pocketbase.io/old/docs/go-records Provides a simple example for deleting a record from PocketBase. It first retrieves the record by its ID and then uses the `DeleteRecord()` method from the DAO to remove it. ```Go record, err := app.Dao().FindRecordById("articles", "RECORD_ID") if err != nil { return err } if err := app.Dao().DeleteRecord(record); err != nil { return err } ``` -------------------------------- ### Query Builder: From Method Source: https://pocketbase.io/old/docs/go-database Explains the `From()` method used to specify the table(s) from which to select data. Table names are automatically quoted for SQL safety. ```APIDOC From(...tables) Specifies the table(s) to select from. Example: app.Dao().DB(). Select("table1.id", "table2.name"). From("table1", "table2") ... ``` -------------------------------- ### PocketBase Admin Authentication and Get One (Dart) Source: https://pocketbase.io/old/docs/api-admins Demonstrates how to authenticate an admin and retrieve a single admin's details using the PocketBase Dart SDK. ```Dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); // Authenticate admin await pb.admins.authWithPassword('test@example.com', '123456'); // Get a single admin by ID const adminId = 'ADMIN_ID'; final admin = await pb.admins.getOne(adminId); print(admin); ``` -------------------------------- ### Build SQL Queries with Where, AndWhere, OrWhere Source: https://pocketbase.io/old/docs/go-database Demonstrates constructing SQL queries using PocketBase IO's dbx library, chaining Where, AndWhere, and OrWhere methods to build complex WHERE clauses. This example shows how to combine different expression types for filtering data. ```go /* SELECT users.* FROM users WHERE id = "someId" AND status = "public" AND name like "%john%" OR ( role = "manager" AND fullTime IS TRUE AND experience > 10 ) */ app.Dao().DB(). Select("users.*"). From("users"). Where(dbx.NewExp("id = {:id}", dbx.Params{ "id": "someId" })). AndWhere(dbx.HashExp{"status": "public"}). AndWhere(dbx.Like("name", "john")), OrWhere(dbx.And( dbx.HashExp{ "role": "manager", "fullTime": true, }, dbx.NewExp("experience > {:exp}", dbx.Params{ "exp": 10 }) )) ... ``` -------------------------------- ### Download PocketBase v0.22.34 Source: https://pocketbase.io/old/docs/index Provides direct download links for the PocketBase v0.22.34 executable across different operating systems and architectures (x64, ARM64). Links are for zip archives. ```Shell wget https://github.com/pocketbase/pocketbase/releases/download/v0.22.34/pocketbase_0.22.34_linux_amd64.zip wget https://github.com/pocketbase/pocketbase/releases/download/v0.22.34/pocketbase_0.22.34_windows_amd64.zip wget https://github.com/pocketbase/pocketbase/releases/download/v0.22.34/pocketbase_0.22.34_darwin_amd64.zip wget https://github.com/pocketbase/pocketbase/releases/download/v0.22.34/pocketbase_0.22.34_linux_arm64.zip wget https://github.com/pocketbase/pocketbase/releases/download/v0.22.34/pocketbase_0.22.34_windows_arm64.zip wget https://github.com/pocketbase/pocketbase/releases/download/v0.22.34/pocketbase_0.22.34_darwin_arm64.zip ``` -------------------------------- ### PocketBase Admin Authentication and Get One (JavaScript) Source: https://pocketbase.io/old/docs/api-admins Demonstrates how to authenticate an admin and retrieve a single admin's details using the PocketBase JavaScript SDK. ```JavaScript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); // Authenticate admin await pb.admins.authWithPassword('test@example.com', '123456'); // Get a single admin by ID const adminId = 'ADMIN_ID'; const admin = await pb.admins.getOne(adminId); console.log(admin); ``` -------------------------------- ### PocketBase Route Helpers: Serve Static Files Source: https://pocketbase.io/old/docs/go-routing Illustrates how to serve static files from a specified directory using `apis.StaticDirectoryHandler`. This is useful for hosting frontend assets or other static content through PocketBase. ```go app.OnBeforeServe().Add(func(e *core.ServeEvent) error { // serves static files from the provided dir (if exists) e.Router.GET("/*", apis.StaticDirectoryHandler(os.DirFS("/path/to/public"), false)) return nil }) ```