pocketbase

package module
v0.0.0-...-47b9678 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 7, 2024 License: MIT Imports: 11 Imported by: 0

README

PocketBase - open source backend in 1 file

build Latest releases Go package documentation

PocketBase is an open source Go backend, consisting of:

  • embedded database (SQLite) with realtime subscriptions
  • built-in files and users management
  • convenient Admin dashboard UI
  • and simple REST-ish API

For documentation and examples, please visit https://pocketbase.io/docs.

[!WARNING] Please keep in mind that PocketBase is still under active development and therefore full backward compatibility is not guaranteed before reaching v1.0.0.

API SDK clients

The easiest way to interact with the API is to use one of the official SDK clients:

Overview

Use as standalone app

You could download the prebuilt executable for your platform from the Releases page. Once downloaded, extract the archive and run ./pocketbase serve in the extracted directory.

The prebuilt executables are based on the examples/base/main.go file and comes with the JS VM plugin enabled by default which allows to extend PocketBase with JavaScript (for more details please refer to Extend with JavaScript).

Use as a Go framework/toolkit

PocketBase is distributed as a regular Go library package which allows you to build your own custom app specific business logic and still have a single portable executable at the end.

Here is a minimal example:

  1. Install Go 1.21+ (if you haven't already)

  2. Create a new project directory with the following main.go file inside it:

    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 main() {
        app := pocketbase.New()
    
        app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
            // add new "GET /hello" route to the app router (echo)
            e.Router.AddRoute(echo.Route{
                Method: http.MethodGet,
                Path:   "/hello",
                Handler: func(c echo.Context) error {
                    return c.String(200, "Hello world!")
                },
                Middlewares: []echo.MiddlewareFunc{
                    apis.ActivityLogger(app),
                },
            })
    
            return nil
        })
    
        if err := app.Start(); err != nil {
            log.Fatal(err)
        }
    }
    
  3. To init the dependencies, run go mod init myapp && go mod tidy.

  4. To start the application, run go run main.go serve.

  5. To build a statically linked executable, you can run CGO_ENABLED=0 go build and then start the created executable with ./myapp serve.

[!NOTE] PocketBase embeds SQLite, but doesn't require CGO.

If CGO is enabled (aka. CGO_ENABLED=1), it will use mattn/go-sqlite3 driver, otherwise - modernc.org/sqlite. Enable CGO only if you really need to squeeze the read/write query performance at the expense of complicating cross compilation.

For more details please refer to Extend with Go.

Building and running the repo main.go example

To build the minimal standalone executable, like the prebuilt ones in the releases page, you can simply run go build inside the examples/base directory:

  1. Install Go 1.21+ (if you haven't already)
  2. Clone/download the repo
  3. Navigate to examples/base
  4. Run GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build (https://go.dev/doc/install/source#environment)
  5. Start the created executable by running ./base serve.

Note that the supported build targets by the pure Go SQLite driver at the moment are:

darwin  amd64
darwin  arm64
freebsd amd64
freebsd arm64
linux   386
linux   amd64
linux   arm
linux   arm64
linux   ppc64le
linux   riscv64
linux   s390x
windows amd64
windows arm64

Testing

PocketBase comes with mixed bag of unit and integration tests. To run them, use the standard go test command:

go test ./...

Check also the Testing guide to learn how to write your own custom application tests.

Security

If you discover a security vulnerability within PocketBase, please send an e-mail to support at pocketbase.io.

All reports will be promptly addressed, and you'll be credited accordingly.

Contributing

PocketBase is free and open source project licensed under the MIT License. You are free to do whatever you want with it, even offering it as a paid service.

You could help continuing its development by:

PRs for new OAuth2 providers, bug fixes, code optimizations and documentation improvements are more than welcome.

But please refrain creating PRs for new features without previously discussing the implementation details. PocketBase has a roadmap and I try to work on issues in specific order and such PRs often come in out of nowhere and skew all initial planning with tedious back-and-forth communication.

Don't get upset if I close your PR, even if it is well executed and tested. This doesn't mean that it will never be merged. Later we can always refer to it and/or take pieces of your implementation when the time comes to work on the issue (don't worry you'll be credited in the release notes).

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Version = "(untracked)"

Version of PocketBase

Functions

This section is empty.

Types

type Config

type Config struct {
	// optional default values for the console flags
	DefaultDev           bool
	DefaultDataDir       string // if not set, it will fallback to "./pb_data"
	DefaultEncryptionEnv string

	// hide the default console server info on app startup
	HideStartBanner bool

	// optional DB configurations
	DataMaxOpenConns int // default to core.DefaultDataMaxOpenConns
	DataMaxIdleConns int // default to core.DefaultDataMaxIdleConns
	LogsMaxOpenConns int // default to core.DefaultLogsMaxOpenConns
	LogsMaxIdleConns int // default to core.DefaultLogsMaxIdleConns
}

Config is the PocketBase initialization config struct.

type PocketBase

type PocketBase struct {

	// RootCmd is the main console command
	RootCmd *cobra.Command
	// contains filtered or unexported fields
}

PocketBase defines a PocketBase app launcher.

It implements core.App via embedding and all of the app interface methods could be accessed directly through the instance (eg. PocketBase.DataDir()).

func New

func New() *PocketBase

New creates a new PocketBase instance with the default configuration. Use [NewWithConfig()] if you want to provide a custom configuration.

Note that the application will not be initialized/bootstrapped yet, aka. DB connections, migrations, app settings, etc. will not be accessible. Everything will be initialized when [Start()] is executed. If you want to initialize the application before calling [Start()], then you'll have to manually call [Bootstrap()].

func NewWithConfig

func NewWithConfig(config Config) *PocketBase

NewWithConfig creates a new PocketBase instance with the provided config.

Note that the application will not be initialized/bootstrapped yet, aka. DB connections, migrations, app settings, etc. will not be accessible. Everything will be initialized when [Start()] is executed. If you want to initialize the application before calling [Start()], then you'll have to manually call [Bootstrap()].

func (*PocketBase) Execute

func (pb *PocketBase) Execute() error

Execute initializes the application (if not already) and executes the pb.RootCmd with graceful shutdown support.

This method differs from pb.Start() by not registering the default system commands!

func (*PocketBase) Start

func (pb *PocketBase) Start() error

Start starts the application, aka. registers the default system commands (serve, migrate, version) and executes pb.RootCmd.

Directories

Path Synopsis
Package apis implements the default PocketBase api services and middlewares.
Package apis implements the default PocketBase api services and middlewares.
Package core is the backbone of PocketBase.
Package core is the backbone of PocketBase.
Package daos handles common PocketBase DB model manipulations.
Package daos handles common PocketBase DB model manipulations.
examples
Package models implements various services used for request data validation and applying changes to existing DB models through the app Dao.
Package models implements various services used for request data validation and applying changes to existing DB models through the app Dao.
validators
Package validators implements custom shared PocketBase validators.
Package validators implements custom shared PocketBase validators.
Package mails implements various helper methods for sending user and admin emails like forgotten password, verification, etc.
Package mails implements various helper methods for sending user and admin emails like forgotten password, verification, etc.
Package migrations contains the system PocketBase DB migrations.
Package migrations contains the system PocketBase DB migrations.
Package models implements all PocketBase DB models and DTOs.
Package models implements all PocketBase DB models and DTOs.
schema
Package schema implements custom Schema and SchemaField datatypes for handling the Collection schema definitions.
Package schema implements custom Schema and SchemaField datatypes for handling the Collection schema definitions.
plugins
ghupdate
Package ghupdate implements a new command to selfupdate the current PocketBase executable with the latest GitHub release.
Package ghupdate implements a new command to selfupdate the current PocketBase executable with the latest GitHub release.
jsvm
Package jsvm implements pluggable utilities for binding a JS goja runtime to the PocketBase instance (loading migrations, attaching to app hooks, etc.).
Package jsvm implements pluggable utilities for binding a JS goja runtime to the PocketBase instance (loading migrations, attaching to app hooks, etc.).
migratecmd
Package migratecmd adds a new "migrate" command support to a PocketBase instance.
Package migratecmd adds a new "migrate" command support to a PocketBase instance.
Package resolvers contains custom search.FieldResolver implementations.
Package resolvers contains custom search.FieldResolver implementations.
Package tests provides common helpers and mocks used in PocketBase application tests.
Package tests provides common helpers and mocks used in PocketBase application tests.
Package tokens implements various user and admin tokens generation methods.
Package tokens implements various user and admin tokens generation methods.
tools
cron
Package cron implements a crontab-like service to execute and schedule repeative tasks/jobs.
Package cron implements a crontab-like service to execute and schedule repeative tasks/jobs.
template
Package template is a thin wrapper around the standard html/template and text/template packages that implements a convenient registry to load and cache templates on the fly concurrently.
Package template is a thin wrapper around the standard html/template and text/template packages that implements a convenient registry to load and cache templates on the fly concurrently.
tokenizer
Package tokenizer implements a rudimentary tokens parser of buffered io.Reader while respecting quotes and parenthesis boundaries.
Package tokenizer implements a rudimentary tokens parser of buffered io.Reader while respecting quotes and parenthesis boundaries.
types
Package types implements some commonly used db serializable types like datetime, json, etc.
Package types implements some commonly used db serializable types like datetime, json, etc.
Package ui handles the PocketBase Admin frontend embedding.
Package ui handles the PocketBase Admin frontend embedding.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL