PocketBase JavaScript API
What every PocketOne app's pb_hooks and page code get from core, before any extension adds its own: the globals ($app and the $-helpers), the hooks, the functions and the classes. Types link to their pages, one per Go namespace (core, dbx, router and the rest). Generated from PocketOne's types.d.ts, the same file your editor reads, so it matches the binary you run. Go names are written in JS form: Go's FindRecordById is findRecordById.
Globals
$app
$app: PocketBase
$app is the current running PocketBase instance that is globally
available in each .pb.js file.
Note that this variable is available only in pb_hooks context.
Type: PocketBase.
$template
$template: template.Registry
$template is a global helper to load and cache HTML templates on the fly.
The templates uses the standard Go html/template and text/template package syntax.
Example:
const html = $template.loadFiles(
"views/layout.html",
"views/content.html",
).render({"name": "John"})
Type: template.Registry.
console
console: Console
Writes to the app's log. @group PocketOne
Type: Console.
module
module: { exports: any; id: string; filename: string; loaded: boolean }
Inside a CommonJS module: the module. @group PocketOne
Type: { exports: any; id: string; filename: string; loaded: boolean }.
exports
exports: any
Inside a CommonJS module: module.exports. @group PocketOne
Type: any.
$dbx
$dbx defines common utility for working with the DB abstraction.
For examples and guides please check the Database guide.
$dbx.hashExp()
$dbx.hashExp(pairs: { [key:string]: any }): dbx.Expression
HashExp represents a hash expression.
A hash expression is a map whose keys are DB column names which need to be filtered according to the corresponding values. For example, HashExp{"level": 2, "dept": 10} will generate the SQL: "level"=2 AND "dept"=10.
HashExp also handles nil values and slice values. For example, HashExp{"level": []interface{}{1, 2}, "dept": nil} will generate: "level" IN (1, 2) AND "dept" IS NULL.
| Parameter | Type |
|---|---|
pairs |
{ [key:string]: any } |
Returns dbx.Expression.
$dbx.in()
$dbx.in(col: string, ...values: { }[]): Expression
In generates an IN expression for the specified column and the list of allowed values. If values is empty, a SQL "0=1" will be generated which represents a false expression.
| Parameter | Type |
|---|---|
col |
string |
...values |
{ }[] (optional) |
Returns Expression.
$dbx.exp()
$dbx.exp(e: string, ...params: Params[]): Expression
NewExp generates an expression with the specified SQL fragment and the optional binding parameters.
| Parameter | Type |
|---|---|
e |
string |
...params |
Params[] (optional) |
Returns Expression.
$dbx.not()
$dbx.not(e: Expression): Expression
Not generates a NOT expression which prefixes "NOT" to the specified expression.
| Parameter | Type |
|---|---|
e |
Expression |
Returns Expression.
$dbx.and()
$dbx.and(...exps: Expression[]): Expression
And generates an AND expression which concatenates the given expressions with "AND".
| Parameter | Type |
|---|---|
...exps |
Expression[] (optional) |
Returns Expression.
$dbx.or()
$dbx.or(...exps: Expression[]): Expression
Or generates an OR expression which concatenates the given expressions with "OR".
| Parameter | Type |
|---|---|
...exps |
Expression[] (optional) |
Returns Expression.
$dbx.notIn()
$dbx.notIn(col: string, ...values: { }[]): Expression
NotIn generates an NOT IN expression for the specified column and the list of disallowed values. If values is empty, an empty string will be returned indicating a true expression.
| Parameter | Type |
|---|---|
col |
string |
...values |
{ }[] (optional) |
Returns Expression.
$dbx.like()
$dbx.like(col: string, ...values: string[]): (LikeExp)
Like generates a LIKE expression for the specified column and the possible strings that the column should be like. If multiple values are present, the column should be like all of them. For example, Like("name", "key", "word") will generate a SQL expression: "name" LIKE "%key%" AND "name" LIKE "%word%".
By default, each value will be surrounded by "%" to enable partial matching. If a value contains special characters such as "%", "", "_", they will also be properly escaped.
You may call Escape() and/or Match() to change the default behavior. For example, Like("name", "key").Match(false, true) generates "name" LIKE "key%".
| Parameter | Type |
|---|---|
col |
string |
...values |
string[] (optional) |
Returns (LikeExp).
$dbx.orLike()
$dbx.orLike(col: string, ...values: string[]): (LikeExp)
OrLike generates an OR LIKE expression. This is similar to Like() except that the column should be like one of the possible values. For example, OrLike("name", "key", "word") will generate a SQL expression: "name" LIKE "%key%" OR "name" LIKE "%word%". Please see Like() for more details.
| Parameter | Type |
|---|---|
col |
string |
...values |
string[] (optional) |
Returns (LikeExp).
$dbx.notLike()
$dbx.notLike(col: string, ...values: string[]): (LikeExp)
NotLike generates a NOT LIKE expression. For example, NotLike("name", "key", "word") will generate a SQL expression: "name" NOT LIKE "%key%" AND "name" NOT LIKE "%word%". Please see Like() for more details.
| Parameter | Type |
|---|---|
col |
string |
...values |
string[] (optional) |
Returns (LikeExp).
$dbx.orNotLike()
$dbx.orNotLike(col: string, ...values: string[]): (LikeExp)
OrNotLike generates an OR NOT LIKE expression. For example, OrNotLike("name", "key", "word") will generate a SQL expression: "name" NOT LIKE "%key%" OR "name" NOT LIKE "%word%". Please see Like() for more details.
| Parameter | Type |
|---|---|
col |
string |
...values |
string[] (optional) |
Returns (LikeExp).
$dbx.exists()
$dbx.exists(exp: Expression): Expression
Exists generates an EXISTS expression by prefixing "EXISTS" to the given expression.
| Parameter | Type |
|---|---|
exp |
Expression |
Returns Expression.
$dbx.notExists()
$dbx.notExists(exp: Expression): Expression
NotExists generates an EXISTS expression by prefixing "NOT EXISTS" to the given expression.
| Parameter | Type |
|---|---|
exp |
Expression |
Returns Expression.
$dbx.between()
$dbx.between(col: string, from: { }, to: { }): Expression
Between generates a BETWEEN expression. For example, Between("age", 10, 30) generates: "age" BETWEEN 10 AND 30
| Parameter | Type |
|---|---|
col |
string |
from |
{ } |
to |
{ } |
Returns Expression.
$dbx.notBetween()
$dbx.notBetween(col: string, from: { }, to: { }): Expression
NotBetween generates a NOT BETWEEN expression. For example, NotBetween("age", 10, 30) generates: "age" NOT BETWEEN 10 AND 30
| Parameter | Type |
|---|---|
col |
string |
from |
{ } |
to |
{ } |
Returns Expression.
$mails
$mails defines helpers to send common
auth records emails like verification, password reset, etc.
$mails.sendRecordPasswordReset()
$mails.sendRecordPasswordReset(app: CoreApp, authRecord: core.Record): void
SendRecordPasswordReset sends a password reset request email to the specified auth record.
| Parameter | Type |
|---|---|
app |
CoreApp |
authRecord |
core.Record |
$mails.sendRecordVerification()
$mails.sendRecordVerification(app: CoreApp, authRecord: core.Record): void
SendRecordVerification sends a verification request email to the specified auth record.
| Parameter | Type |
|---|---|
app |
CoreApp |
authRecord |
core.Record |
$mails.sendRecordChangeEmail()
$mails.sendRecordChangeEmail(app: CoreApp, authRecord: core.Record, newEmail: string): void
SendRecordChangeEmail sends a change email confirmation email to the specified auth record.
| Parameter | Type |
|---|---|
app |
CoreApp |
authRecord |
core.Record |
newEmail |
string |
$mails.sendRecordOTP()
$mails.sendRecordOTP(app: CoreApp, authRecord: core.Record, otpId: string, pass: string): void
SendRecordOTP sends OTP email to the specified auth record.
This method will also update the "sentTo" field of the related OTP record to the mail sent To address (if the OTP exists and not already assigned).
| Parameter | Type |
|---|---|
app |
CoreApp |
authRecord |
core.Record |
otpId |
string |
pass |
string |
$mails.sendRecordAuthAlert()
$mails.sendRecordAuthAlert(app: CoreApp, authRecord: core.Record, info: string): void
SendRecordAuthAlert sends a new device login alert to the specified auth record.
| Parameter | Type |
|---|---|
app |
CoreApp |
authRecord |
core.Record |
info |
string |
$security
$security defines low level helpers for creating
and parsing JWTs, random string generation, AES encryption, etc.
$security.randomString()
$security.randomString(length: number): string
RandomString generates a cryptographically random string with the specified length.
The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding.
| Parameter | Type |
|---|---|
length |
number |
Returns string.
$security.randomStringWithAlphabet()
$security.randomStringWithAlphabet(length: number, alphabet: string): string
RandomStringWithAlphabet generates a cryptographically random string with the specified length and characters set.
It panics if for some reason rand.Int returns a non-nil error.
| Parameter | Type |
|---|---|
length |
number |
alphabet |
string |
Returns string.
$security.randomStringByRegex()
$security.randomStringByRegex(pattern: string, ...optFlags: syntax.Flags[]): string
RandomStringByRegex generates a random string matching the regex pattern.
If optFlags is not set, fallbacks to syntax.perl.
NB! While the source of the randomness comes from [crypto/rand] this method
is not recommended to be used on its own in critical secure contexts because
the generated length could vary too much on the used pattern and may not be
as secure as simply calling security.randomString.
If you still insist on using it for such purposes, consider at least
a large enough minimum length for the generated string, e.g. [a-z0-9]{30}.
This function is inspired by github.com/pipe01/revregexp, github.com/lucasjones/reggen and other similar packages.
| Parameter | Type |
|---|---|
pattern |
string |
...optFlags |
syntax.Flags[] (optional) |
Returns string.
$security.pseudorandomString()
$security.pseudorandomString(length: number): string
PseudorandomString generates a pseudorandom string with the specified length.
The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding.
For a cryptographically random string (but a little bit slower) use RandomString instead.
| Parameter | Type |
|---|---|
length |
number |
Returns string.
$security.pseudorandomStringWithAlphabet()
$security.pseudorandomStringWithAlphabet(length: number, alphabet: string): string
PseudorandomStringWithAlphabet generates a pseudorandom string with the specified length and characters set.
For a cryptographically random (but a little bit slower) use RandomStringWithAlphabet instead.
| Parameter | Type |
|---|---|
length |
number |
alphabet |
string |
Returns string.
$security.encrypt()
$security.encrypt(data: string|Array<number>, key: string): string
Encrypt encrypts "data" with the specified "key" (must be valid 32 char AES key).
This method uses AES-256-GCM block cypher mode.
| Parameter | Type |
|---|---|
data |
string|Array<number> |
key |
string |
Returns string.
$security.decrypt()
$security.decrypt(cipherText: string, key: string): string|Array<number>
Decrypt decrypts encrypted text with key (must be valid 32 chars AES key).
This method uses AES-256-GCM block cypher mode.
| Parameter | Type |
|---|---|
cipherText |
string |
key |
string |
Returns string|Array<number>.
$security.hs256()
$security.hs256(text: string, secret: string): string
HS256 creates a HMAC hash with sha256 digest algorithm.
| Parameter | Type |
|---|---|
text |
string |
secret |
string |
Returns string.
$security.hs512()
$security.hs512(text: string, secret: string): string
HS512 creates a HMAC hash with sha512 digest algorithm.
| Parameter | Type |
|---|---|
text |
string |
secret |
string |
Returns string.
$security.equal()
$security.equal(hash1: string, hash2: string): boolean
Equal compares two hash strings for equality without leaking timing information.
| Parameter | Type |
|---|---|
hash1 |
string |
hash2 |
string |
Returns boolean.
$security.md5()
$security.md5(text: string): string
MD5 creates md5 hash from the provided plain text.
| Parameter | Type |
|---|---|
text |
string |
Returns string.
$security.sha256()
$security.sha256(text: string): string
SHA256 creates sha256 hash as defined in FIPS 180-4 from the provided text.
| Parameter | Type |
|---|---|
text |
string |
Returns string.
$security.sha512()
$security.sha512(text: string): string
SHA512 creates sha512 hash as defined in FIPS 180-4 from the provided text.
| Parameter | Type |
|---|---|
text |
string |
Returns string.
$security.createJWT()
$security.createJWT(payload: { [key:string]: any }, signingKey: string, secDuration: number): string
NewJWT generates and returns new HS256 signed JWT.
| Parameter | Type |
|---|---|
payload |
{ [key:string]: any } |
signingKey |
string |
secDuration |
number |
Returns string.
$security.parseUnverifiedJWT()
$security.parseUnverifiedJWT(token: string): _TygojaDict
ParseUnverifiedJWT parses JWT and returns its claims but DOES NOT verify the signature.
It verifies only the exp, iat and nbf claims.
| Parameter | Type |
|---|---|
token |
string |
Returns { [key: string]: any }.
$security.parseJWT()
$security.parseJWT(token: string, verificationKey: string): _TygojaDict
ParseJWT verifies and parses JWT and returns its claims.
| Parameter | Type |
|---|---|
token |
string |
verificationKey |
string |
Returns { [key: string]: any }.
$filesystem
$filesystem defines common helpers for working
with the PocketBase filesystem abstraction.
$filesystem.fileFromPath()
$filesystem.fileFromPath(path: string): (File)
NewFileFromPath creates a new File instance from the provided local file path.
| Parameter | Type |
|---|---|
path |
string |
Returns (File).
$filesystem.fileFromBytes()
$filesystem.fileFromBytes(b: string|Array<number>, name: string): (File)
NewFileFromBytes creates a new File instance from the provided byte slice.
| Parameter | Type |
|---|---|
b |
string|Array<number> |
name |
string |
Returns (File).
$filesystem.fileFromMultipart()
$filesystem.fileFromMultipart(mh: multipart.FileHeader): (File)
NewFileFromMultipart creates a new File from the provided multipart header.
| Parameter | Type |
|---|---|
mh |
multipart.FileHeader |
Returns (File).
$filesystem.s3()
$filesystem.s3(bucketName: string, region: string, endpoint: string, accessKey: string, secretKey: string, s3ForcePathStyle: boolean): (System)
Initializes a new S3-only filesystem instance
(make sure to call close() after you are done working with it).
Most users should prefer $app.newFilesystem() which will
construct a local or S3 filesystem based on the configured application settings.
| Parameter | Type |
|---|---|
bucketName |
string |
region |
string |
endpoint |
string |
accessKey |
string |
secretKey |
string |
s3ForcePathStyle |
boolean |
Returns (System).
$filesystem.local()
$filesystem.local(dirPath: string): (System)
Initializes a new local-only filesystem instance
(make sure to call close() after you are done working with it).
Most users should prefer $app.newFilesystem() which will
construct a local or S3 filesystem based on the configured application settings.
| Parameter | Type |
|---|---|
dirPath |
string |
Returns (System).
$filesystem.fileFromURL()
$filesystem.fileFromURL(url: string, secTimeout?: number): filesystem.File
fileFromURL creates a new File from the provided url by downloading the resource and creating a BytesReader.
Example:
// with default max timeout of 120sec
const file1 = $filesystem.fileFromURL("https://...")
// with custom timeout of 15sec
const file2 = $filesystem.fileFromURL("https://...", 15)
| Parameter | Type |
|---|---|
url |
string |
secTimeout |
number (optional) |
Returns filesystem.File.
$filepath
$filepath defines common helpers for manipulating filename
paths in a way compatible with the target operating system-defined file paths.
$filepath.base()
$filepath.base(path: string): string
Base returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of separators, Base returns a single separator.
| Parameter | Type |
|---|---|
path |
string |
Returns string.
$filepath.clean()
$filepath.clean(path: string): string
Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done:
- Replace multiple
Separatorelements with a single one. - Eliminate each . path name element (the current directory).
- Eliminate each inner .. path name element (the parent directory)
along with the non-.. element that precedes it.
- Eliminate .. elements that begin a rooted path:
that is, replace "/.." by "/" at the beginning of a path,
assuming Separator is '/'.
The returned path ends in a slash only if it represents a root directory,
such as "/" on Unix or C:\ on Windows.
Finally, any occurrences of slash are replaced by Separator.
If the result of this process is an empty string, Clean returns the string ".".
On Windows, Clean does not modify the volume name other than to replace
occurrences of "/" with \.
For example, Clean("//host/share/../x") returns \\host\share\x.
See also Rob Pike, “Lexical File Names in Plan 9 or Getting Dot-Dot Right,” https://9p.io/sys/doc/lexnames.html
| Parameter | Type |
|---|---|
path |
string |
Returns string.
$filepath.dir()
$filepath.dir(path: string): string
Dir returns all but the last element of path, typically the path's directory.
After dropping the final element, Dir calls Clean on the path and trailing
slashes are removed.
If the path is empty, Dir returns ".".
If the path consists entirely of separators, Dir returns a single separator.
The returned path does not end in a separator unless it is the root directory.
On Windows, given a volume-only name such as "C:", Dir returns "C:.",
the current directory on drive C. To obtain the drive's root "C:",
use VolumeName combined with a separator.
| Parameter | Type |
|---|---|
path |
string |
Returns string.
$filepath.ext()
$filepath.ext(path: string): string
Ext returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final element of path; it is empty if there is no dot.
| Parameter | Type |
|---|---|
path |
string |
Returns string.
$filepath.fromSlash()
$filepath.fromSlash(path: string): string
FromSlash returns the result of replacing each slash ('/') character in path with a separator character. Multiple slashes are replaced by multiple separators.
See also the Localize function, which converts a slash-separated path as used by the io/fs package to an operating system path.
| Parameter | Type |
|---|---|
path |
string |
Returns string.
$filepath.glob()
$filepath.glob(pattern: string): Array<string>
Glob returns the names of all files matching pattern or nil
if there is no matching file. The syntax of patterns is the same
as in Match. The pattern may describe hierarchical names such as
/usr/*/bin/ed (assuming the Separator is '/').
Glob ignores file system errors such as I/O errors reading directories.
The only possible returned error is ErrBadPattern, when pattern
is malformed.
| Parameter | Type |
|---|---|
pattern |
string |
Returns Array<string>.
$filepath.isAbs()
$filepath.isAbs(path: string): boolean
IsAbs reports whether the path is absolute.
| Parameter | Type |
|---|---|
path |
string |
Returns boolean.
$filepath.join()
$filepath.join(...elem: string[]): string
Join joins any number of path elements into a single path,
separating them with an OS specific Separator. Empty elements
are ignored. The result is Cleaned. However, if the argument
list is empty or all its elements are empty, Join returns
an empty string.
On Windows, the result will only be a UNC path if the first
non-empty element is a UNC path.
| Parameter | Type |
|---|---|
...elem |
string[] (optional) |
Returns string.
$filepath.match()
$filepath.match(pattern: string, name: string): boolean
Match reports whether name matches the shell file name pattern. The pattern syntax is:
pattern:
{ term }
term:
'*' matches any sequence of non-Separator characters
'?' matches any single non-Separator character
'[' [ '^' ] { character-range } ']'
character class (must be non-empty)
c matches character c (c != '*', '?', '\\', '[')
'\\' c matches character c (except on Windows)
character-range:
c matches character c (c != '\\', '-', ']')
'\\' c matches character c (except on Windows)
lo '-' hi matches character c for lo <= c <= hi
Path segments in the pattern must be separated by Separator.
Match requires pattern to match all of name, not just a substring.
The only possible returned error is ErrBadPattern, when pattern
is malformed.
On Windows, escaping is disabled. Instead, '\' is treated as path separator.
| Parameter | Type |
|---|---|
pattern |
string |
name |
string |
Returns boolean.
$filepath.rel()
$filepath.rel(basePath: string, targPath: string): string
Rel returns a relative path that is lexically equivalent to targPath when joined to basePath with an intervening separator. That is, [Join](basePath, Rel(basePath, targPath)) is equivalent to targPath itself.
The returned path will always be relative to basePath, even if basePath and
targPath share no elements. Rel calls Clean on the result.
An error is returned if targPath can't be made relative to basePath or if knowing the current working directory would be necessary to compute it.
| Parameter | Type |
|---|---|
basePath |
string |
targPath |
string |
Returns string.
$filepath.split()
$filepath.split(path: string): [string, string]
Split splits path immediately following the final Separator,
separating it into a directory and file name component.
If there is no Separator in path, Split returns an empty dir
and file set to path.
The returned values have the property that path = dir+file.
| Parameter | Type |
|---|---|
path |
string |
Returns [string, string].
$filepath.splitList()
$filepath.splitList(path: string): Array<string>
SplitList splits a list of paths joined by the OS-specific ListSeparator,
usually found in PATH or GOPATH environment variables.
Unlike strings.Split, SplitList returns an empty slice when passed an empty
string.
| Parameter | Type |
|---|---|
path |
string |
Returns Array<string>.
$filepath.toSlash()
$filepath.toSlash(path: string): string
ToSlash returns the result of replacing each separator character in path with a slash ('/') character. Multiple separators are replaced by multiple slashes.
| Parameter | Type |
|---|---|
path |
string |
Returns string.
$filepath.walk()
$filepath.walk(root: string, fn: WalkFunc): void
Walk walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.
All errors that arise visiting files and directories are filtered by fn:
see the WalkFunc documentation for details.
The files are walked in lexical order, which makes the output deterministic but requires Walk to read an entire directory into memory before proceeding to walk that directory.
Walk does not follow symbolic links.
Walk is less efficient than WalkDir, introduced in Go 1.16,
which avoids calling os.Lstat on every visited file or directory.
| Parameter | Type |
|---|---|
root |
string |
fn |
WalkFunc |
$filepath.walkDir()
$filepath.walkDir(root: string, fn: fs.WalkDirFunc): void
WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.
All errors that arise visiting files and directories are filtered by fn:
see the fs.walkDirFunc documentation for details.
The files are walked in lexical order, which makes the output deterministic but requires WalkDir to read an entire directory into memory before proceeding to walk that directory.
WalkDir does not follow symbolic links.
WalkDir calls fn with paths that use the separator character appropriate for the operating system. This is unlike [io/fs.WalkDir], which always uses slash separated paths.
| Parameter | Type |
|---|---|
root |
string |
fn |
fs.WalkDirFunc |
$os
$os defines common helpers for working with the OS level primitives
(eg. deleting directories, executing shell commands, etc.).
$os.exec()
$os.exec(name: string, ...arg: string[]): (Cmd)
Legacy alias for $os.cmd().
| Parameter | Type |
|---|---|
name |
string |
...arg |
string[] (optional) |
Returns (Cmd).
$os.cmd()
$os.cmd(name: string, ...arg: string[]): (Cmd)
Prepares an external OS command.
Example:
// prepare the command to execute
const cmd = $os.cmd('ls', '-sl')
// execute the command and return its standard output as string
const output = toString(cmd.output());
| Parameter | Type |
|---|---|
name |
string |
...arg |
string[] (optional) |
Returns (Cmd).
$os.args
$os.args: Array<string>
Args hold the command-line arguments, starting with the program name.
Returns Array<string>.
$os.exit()
$os.exit(code: number): void
Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error. The program terminates immediately; deferred functions are not run.
For portability, the status code should be in the range [0, 125].
| Parameter | Type |
|---|---|
code |
number |
$os.getenv()
$os.getenv(key: string): string
Getenv retrieves the value of the environment variable named by the key.
It returns the value, which will be empty if the variable is not present.
To distinguish between an empty value and an unset value, use LookupEnv.
| Parameter | Type |
|---|---|
key |
string |
Returns string.
$os.dirFS()
$os.dirFS(dir: string): fs.FS
DirFS returns a file system (an fs.FS) for the tree of files rooted at the directory dir.
Note that DirFS("/prefix") only guarantees that the Open calls it makes to the operating system will begin with "/prefix": DirFS("/prefix").Open("file") is the same as os.Open("/prefix/file"). So if /prefix/file is a symbolic link pointing outside the /prefix tree, then using DirFS does not stop the access any more than using os.Open does. Additionally, the root of the fs.FS returned for a relative path, DirFS("prefix"), will be affected by later calls to Chdir. DirFS is therefore not a general substitute for a chroot-style security mechanism when the directory tree contains arbitrary content.
Use Root.fS to obtain a fs.FS that prevents escapes from the tree via symbolic links.
The directory dir must not be "".
The result implements [io/fs.StatFS], [io/fs.ReadFileFS], [io/fs.ReadDirFS], and [io/fs.ReadLinkFS].
| Parameter | Type |
|---|---|
dir |
string |
Returns fs.FS.
$os.readFile()
$os.readFile(name: string): string|Array<number>
ReadFile reads the named file and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported. If there is an error, it will be of type [*PathError].
| Parameter | Type |
|---|---|
name |
string |
Returns string|Array<number>.
$os.writeFile()
$os.writeFile(name: string, data: string|Array<number>, perm: FileMode): void
WriteFile writes data to the named file, creating it if necessary. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions. Since WriteFile requires multiple system calls to complete, a failure mid-operation can leave the file in a partially written state.
| Parameter | Type |
|---|---|
name |
string |
data |
string|Array<number> |
perm |
FileMode |
$os.stat()
$os.stat(name: string): FileInfo
Stat returns a FileInfo describing the named file.
If there is an error, it will be of type [*PathError].
| Parameter | Type |
|---|---|
name |
string |
Returns FileInfo.
$os.readDir()
$os.readDir(name: string): Array<DirEntry>
ReadDir reads the named directory, returning all its directory entries sorted by filename. If an error occurs reading the directory, ReadDir returns the entries it was able to read before the error, along with the error.
| Parameter | Type |
|---|---|
name |
string |
Returns Array<DirEntry>.
$os.tempDir()
$os.tempDir(): string
TempDir returns the default directory to use for temporary files.
On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On Windows, it uses GetTempPath, returning the first non-empty value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. On Plan 9, it returns /tmp.
The directory is neither guaranteed to exist nor have accessible permissions.
Returns string.
$os.truncate()
$os.truncate(name: string, size: number): void
Truncate changes the size of the named file. If the file is a symbolic link, it changes the size of the link's target. If there is an error, it will be of type [*PathError].
| Parameter | Type |
|---|---|
name |
string |
size |
number |
$os.getwd()
$os.getwd(): string
Getwd returns an absolute path name corresponding to the current directory. If the current directory can be reached via multiple paths (due to symbolic links), Getwd may return any one of them.
On Unix platforms, if the environment variable PWD provides an absolute name, and it is a name of the current directory, it is returned.
Returns string.
$os.mkdir()
$os.mkdir(name: string, perm: FileMode): void
Mkdir creates a new directory with the specified name and permission bits (before umask). If there is an error, it will be of type [*PathError].
| Parameter | Type |
|---|---|
name |
string |
perm |
FileMode |
$os.mkdirAll()
$os.mkdirAll(path: string, perm: FileMode): void
MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm (before umask) are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.
| Parameter | Type |
|---|---|
path |
string |
perm |
FileMode |
$os.rename()
$os.rename(oldpath: string, newpath: string): void
Rename renames (moves) oldpath to newpath. If newpath already exists and is not a directory, Rename replaces it. If newpath already exists and is a directory, Rename returns an error. OS-specific restrictions may apply when oldpath and newpath are in different directories. Even within the same directory, on non-Unix platforms Rename is not an atomic operation. If there is an error, it will be of type *LinkError.
| Parameter | Type |
|---|---|
oldpath |
string |
newpath |
string |
$os.remove()
$os.remove(name: string): void
Remove removes the named file or (empty) directory. If there is an error, it will be of type [*PathError].
| Parameter | Type |
|---|---|
name |
string |
$os.removeAll()
$os.removeAll(path: string): void
RemoveAll removes path and any children it contains. It removes everything it can but returns the first error it encounters. If the path does not exist, RemoveAll returns nil (no error). If there is an error, it will be of type [*PathError].
| Parameter | Type |
|---|---|
path |
string |
$os.openRoot()
$os.openRoot(name: string): (Root)
OpenRoot opens the named directory. It follows symbolic links in the directory name. If there is an error, it will be of type [*PathError].
| Parameter | Type |
|---|---|
name |
string |
Returns (Root).
$os.openInRoot()
$os.openInRoot(dir: string, name: string): (File)
OpenInRoot opens the file name in the directory dir. It is equivalent to OpenRoot(dir) followed by opening the file in the root.
OpenInRoot returns an error if any component of the name references a location outside of dir.
See Root for details and limitations.
| Parameter | Type |
|---|---|
dir |
string |
name |
string |
Returns (File).
$apis
$apis defines commonly used PocketBase api helpers and middlewares.
$apis.static()
$apis.static(dirOrFS: string|fs.FS, indexFallback: boolean): (e: core.RequestEvent) => void
Route handler to serve static directory content (html, js, css, etc.).
If a file resource is missing and indexFallback is true, the request will be forwarded to the base index.html (useful for SPA with pretty urls).
NB! Expects the route to have a "{path...}" wildcard parameter.
Special redirects:
- if "path" is a file that ends in index.html, it is redirected to its non-index.html version (eg. /test/index.html -> /test/)
- if "path" is a directory that has index.html, the index.html file is rendered, otherwise if missing - returns 404 or fallback to the root index.html if indexFallback is true
Example:
// serves static files from the provided dir string path (it will be wrapped in $os.dirFS())
routerAdd("GET", "/{path...}", $apis.static("/path/to/public", false))
// serves static files from the explicit fs.FS value ($os.dirFS(), $os.openRoot().fs(), etc.)
routerAdd("GET", "/{path...}", $apis.static($os.dirFS("/path/to/public"), false))
| Parameter | Type |
|---|---|
dirOrFS |
string|fs.FS |
indexFallback |
boolean |
Returns (e: core.RequestEvent) => void.
$apis.requireGuestOnly()
$apis.requireGuestOnly(): (hook.Handler<core.RequestEvent | undefined>)
RequireGuestOnly middleware requires a request to NOT have a valid Authorization header.
This middleware is the opposite of [apis.RequireAuth()].
Returns (hook.Handler<core.RequestEvent | undefined>).
$apis.requireAuth()
$apis.requireAuth(...optCollectionNames: string[]): (hook.Handler<core.RequestEvent | undefined>)
RequireAuth middleware requires a request to have a valid record Authorization header.
The auth record could be from any collection. You can further filter the allowed record auth collections by specifying their names.
Example:
apis.RequireAuth() // any auth collection
apis.RequireAuth("_superusers", "users") // only the listed auth collections
| Parameter | Type |
|---|---|
...optCollectionNames |
string[] (optional) |
Returns (hook.Handler<core.RequestEvent | undefined>).
$apis.requireSuperuserAuth()
$apis.requireSuperuserAuth(): (hook.Handler<core.RequestEvent | undefined>)
RequireSuperuserAuth middleware requires a request to have a valid superuser Authorization header.
Returns (hook.Handler<core.RequestEvent | undefined>).
$apis.requireSuperuserOrOwnerAuth()
$apis.requireSuperuserOrOwnerAuth(ownerIdPathParam: string): (hook.Handler<core.RequestEvent | undefined>)
RequireSuperuserOrOwnerAuth middleware requires a request to have a valid superuser or regular record owner Authorization header set.
This middleware is similar to [apis.RequireAuth()] but for the auth record token expects to have the same id as the path parameter ownerIdPathParam (default to "id" if empty).
| Parameter | Type |
|---|---|
ownerIdPathParam |
string |
Returns (hook.Handler<core.RequestEvent | undefined>).
$apis.skipSuccessActivityLog()
$apis.skipSuccessActivityLog(): (hook.Handler<core.RequestEvent | undefined>)
SkipSuccessActivityLog is a helper middleware that instructs the global activity logger to log only requests that have failed/returned an error.
Returns (hook.Handler<core.RequestEvent | undefined>).
$apis.gzip()
$apis.gzip(): (hook.Handler<core.RequestEvent | undefined>)
Gzip returns a middleware which compresses HTTP response using Gzip compression scheme.
Returns (hook.Handler<core.RequestEvent | undefined>).
$apis.bodyLimit()
$apis.bodyLimit(limitBytes: number): (hook.Handler<core.RequestEvent | undefined>)
BodyLimit returns a middleware handler that changes the default request body size limit.
If limitBytes <= 0, no limit is applied.
Otherwise, if the request body size exceeds the configured limitBytes, it sends 413 error response.
| Parameter | Type |
|---|---|
limitBytes |
number |
Returns (hook.Handler<core.RequestEvent | undefined>).
$apis.enrichRecord()
$apis.enrichRecord(e: core.RequestEvent, record: core.Record, ...defaultExpands: string[]): void
EnrichRecord parses the request context and enrich the provided record:
- expands relations (if defaultExpands and/or ?expand query param is set)
- ensures that the emails of the auth record and its expanded auth relations
are visible only for the current logged superuser, record owner or record with manage access
| Parameter | Type |
|---|---|
e |
core.RequestEvent |
record |
core.Record |
...defaultExpands |
string[] (optional) |
$apis.enrichRecords()
$apis.enrichRecords(e: core.RequestEvent, records: Array<(core.Record | undefined)>, ...defaultExpands: string[]): void
EnrichRecords parses the request context and enriches the provided records:
- expands relations (if defaultExpands and/or ?expand query param is set)
- ensures that the emails of the auth records and their expanded auth relations
are visible only for the current logged superuser, record owner or record with manage access
Note: Expects all records to be from the same collection!
| Parameter | Type |
|---|---|
e |
core.RequestEvent |
records |
Array<(core.Record | undefined)> |
...defaultExpands |
string[] (optional) |
$apis.recordAuthResponse()
$apis.recordAuthResponse(e: core.RequestEvent, authRecord: core.Record, authMethod: string, meta?: any): void
RecordAuthResponse writes standardized json record auth response into the specified request event.
The authMethod argument specify the name of the current authentication method (eg. password, oauth2, etc.) that it is used primarily as an auth identifier during MFA and for login alerts.
Set authMethod to empty string if you want to ignore the MFA checks and the login alerts (can be also adjusted additionally via the onRecordAuthRequest hook).
| Parameter | Type |
|---|---|
e |
core.RequestEvent |
authRecord |
core.Record |
authMethod |
string |
meta |
any (optional) |
$http
$http defines common methods for working with HTTP requests.
$http.send()
$http.send(config: { url: string, body?: string|FormData, method?: string, // default to "GET" headers?: { [key:string]: string }, timeout?: number, // default to 120 // @deprecated please use body instead data?: { [key:string]: any }, }): { statusCode: number, headers: { [key:string]: Array<string> }, cookies: { [key:string]: http.Cookie }, json: any, body: Array<number>, // @deprecated please use toString(result.body) instead raw: string, }
Sends a single HTTP request.
Example:
const res = $http.send({
method: "POST",
url: "https://example.com",
body: JSON.stringify({"title": "test"}),
headers: { 'Content-Type': 'application/json' }
})
console.log(res.statusCode) // the response HTTP status code
console.log(res.headers) // the response headers (eg. res.headers['X-Custom'][0])
console.log(res.cookies) // the response cookies (eg. res.cookies.sessionId.value)
console.log(res.body) // the response body as raw bytes slice
console.log(res.json) // the response body as parsed json array or map
| Parameter | Type |
|---|---|
config |
{ url: string, body?: string|FormData, method?: string, // default to "GET" headers?: { [key:string]: string }, timeout?: number, // default to 120 // @deprecated please use body instead data?: { [key:string]: any }, } |
Returns { statusCode: number, headers: { [key:string]: Array<string> }, cookies: { [key:string]: http.Cookie }, json: any, body: Array<number>, // @deprecated please use toString(result.body) instead raw: string, }.
Functions
cronAdd()
cronAdd(jobId: string, cronExpr: string, handler: () => void): void
CronAdd registers a new cron job.
If a cron job with the specified name already exist, it will be replaced with the new one.
Example:
// prints "Hello world!" on every 30 minutes
cronAdd("hello", "*\/30 * * * *", () => {
console.log("Hello world!")
})
Note that this method is available only in pb_hooks context.
| Parameter | Type |
|---|---|
jobId |
string |
cronExpr |
string |
handler |
() => void |
cronRemove()
cronRemove(jobId: string): void
CronRemove removes a single registered cron job by its name.
Example:
cronRemove("hello")
Note that this method is available only in pb_hooks context.
| Parameter | Type |
|---|---|
jobId |
string |
routerAdd()
routerAdd(method: string, path: string, handler: (e: core.RequestEvent) => void, ...middlewares: Array<string|((e: core.RequestEvent) => void)|Middleware>): void
RouterAdd registers a new route definition.
Example:
routerAdd("GET", "/hello", (e) => {
return e.json(200, {"message": "Hello!"})
}, $apis.requireAuth())
Note that this method is available only in pb_hooks context.
| Parameter | Type |
|---|---|
method |
string |
path |
string |
handler |
(e: core.RequestEvent) => void |
...middlewares |
Array<string|((e: core.RequestEvent) => void)|Middleware> (optional) |
routerUse()
routerUse(...middlewares: Array<string|((e: core.RequestEvent) => void)|Middleware>): void
RouterUse registers one or more global middlewares that are executed along the handler middlewares after a matching route is found.
Example:
routerUse((e) => {
console.log(e.request.url.path)
return e.next()
})
Note that this method is available only in pb_hooks context.
| Parameter | Type |
|---|---|
...middlewares |
Array<string|((e: core.RequestEvent) => void)|Middleware> (optional) |
readerToString()
readerToString(reader: any, maxBytes?: number): string
This method is superseded by toString.
| Parameter | Type |
|---|---|
reader |
any |
maxBytes |
number (optional) |
Returns string.
toString()
toString(val: any, maxBytes?: number): string
toString stringifies the specified value.
Support optional second maxBytes argument to limit the max read bytes when the value is a io.Reader (default to 32MB).
Types that don't have explicit string representation are json serialized.
Example:
// io.Reader
const ex1 = toString(e.request.body)
// slice of bytes
const ex2 = toString([104 101 108 108 111]) // "hello"
// null
const ex3 = toString(null) // ""
| Parameter | Type |
|---|---|
val |
any |
maxBytes |
number (optional) |
Returns string.
toBytes()
toBytes(val: any, maxBytes?: number): Array<number>
toBytes converts the specified value into a bytes slice.
Support optional second maxBytes argument to limit the max read bytes when the value is a io.Reader (default to 32MB).
Types that don't have Go slice representation (bool, objects, etc.) are serialized to UTF8 string and its bytes slice is returned.
Example:
// io.Reader
const ex1 = toBytes(e.request.body)
// string
const ex2 = toBytes("hello") // [104 101 108 108 111]
// object (the same as the string '{"test":1}')
const ex3 = toBytes({"test":1}) // [123 34 116 101 115 116 34 58 49 125]
// null
const ex4 = toBytes(null) // []
| Parameter | Type |
|---|---|
val |
any |
maxBytes |
number (optional) |
Returns Array<number>.
sleep()
sleep(milliseconds: number): void
sleep pauses the current goroutine for at least the specified user duration (in ms). A zero or negative duration returns immediately.
Example:
sleep(250) // sleeps for 250ms
| Parameter | Type |
|---|---|
milliseconds |
number |
arrayOf()
arrayOf(model: T): Array<T>
arrayOf creates a placeholder array of the specified models. Usually used to populate DB result into an array of models.
Example:
const records = arrayOf(new Record)
$app.recordQuery("articles").limit(10).all(records)
| Parameter | Type |
|---|---|
model |
T |
Returns Array<T>.
unmarshal()
unmarshal(data: any, dst: any): void
unmarshal clones and merges the data argument on top of dst.
This method is rarely used directly by the users and it is most commonly used in the autogenerated migrations.
To an extent it is similar to the JS native Object.assign
but the arguments are reversed and it invokes the Go standard
json.Marshal/Unmarshal methods under the hood.
The data argument could be anything serializable, usually a plain object (map). The dst argument could be any pointer value, usually a model instance.
Example:
unmarshal({ authAlert: { enabled: true } }, collection)
| Parameter | Type |
|---|---|
data |
any |
dst |
any |
nullString()
nullString(): string
nullString creates an empty Go string pointer usually used for
describing a nullable DynamicModel string value.
Returns string.
nullInt()
nullInt(): number
nullInt creates an empty Go int64 pointer usually used for
describing a nullable DynamicModel int value.
Returns number.
nullFloat()
nullFloat(): number
nullFloat creates an empty Go float64 pointer usually used for
describing a nullable DynamicModel float value.
Returns number.
nullBool()
nullBool(): boolean
nullBool creates an empty Go bool pointer usually used for
describing a nullable DynamicModel bool value.
Returns boolean.
nullArray()
nullArray(): Array<any>
nullArray creates an empty Go types.JSONArray pointer usually used for
describing a nullable DynamicModel JSON array value.
Returns Array<any>.
nullObject()
nullObject(): { get(key:string):any; set(key:string,value:any):void }
nullObject creates an empty Go types.JSONMap pointer usually used for
describing a nullable DynamicModel JSON object value.
Returns { get(key:string):any; set(key:string,value:any):void }.
migrate()
migrate(up: (txApp: CoreApp) => void, down?: (txApp: CoreApp) => void): void
Migrate defines a single migration upgrade/downgrade action.
Note that this method is available only in pb_migrations context.
| Parameter | Type |
|---|---|
up |
(txApp: CoreApp) => void |
down |
(txApp: CoreApp) => void (optional) |
setTimeout()
setTimeout(callback: (...args: A) => void, ms?: number, ...args: A): number
Runs callback(...args) once after ms milliseconds (at least 1), as its own task. A timer set while a request is
served is cleared once the request is answered or its client goes away; one set at the top of a file runs until
cleared. Returns the id for clearTimeout.
const word = await new Promise((resolve) => setTimeout(resolve, 500, "later"))
| Parameter | Type |
|---|---|
callback |
(...args: A) => void |
ms |
number (optional) |
...args |
A (optional) |
Returns number.
setInterval()
setInterval(callback: (...args: A) => void, ms?: number, ...args: A): number
Runs callback(...args) every ms milliseconds (at least 1); the next run is timed from the end of the last one.
Cleared like setTimeout. Returns the id for clearInterval.
| Parameter | Type |
|---|---|
callback |
(...args: A) => void |
ms |
number (optional) |
...args |
A (optional) |
Returns number.
clearTimeout()
clearTimeout(id: number | undefined | null): void
Cancels a setTimeout (an unknown id does nothing). @group PocketOne
| Parameter | Type |
|---|---|
id |
number | undefined | null |
clearInterval()
clearInterval(id: number | undefined | null): void
Cancels a setInterval (an unknown id does nothing). @group PocketOne
| Parameter | Type |
|---|---|
id |
number | undefined | null |
queueMicrotask()
queueMicrotask(callback: () => void): void
Runs callback after the current task, before any timer. @group PocketOne
| Parameter | Type |
|---|---|
callback |
() => void |
require()
require(id: string): any
Loads a CommonJS module (.js, .cjs, .cts, .json, a node_modules package) or an ES module without top-level
await (.mjs, .ts, .mts), relative to the calling file. A module loads once per app.
| Parameter | Type |
|---|---|
id |
string |
Returns any.
Classes
DynamicModel
new (shape?: { [key:string]: any })
DynamicModel creates a new dynamic model with fields from the provided data shape.
Caveats:
- In order to use 0 as double/float initialization number you have to negate it (
-0). - You need to use lowerCamelCase when accessing the model fields (e.g.
model.rolesand notmodel.Roleseven if in the model shape and in the DB table the column is capitalized). - Objects are loaded into types.JSONMap, meaning that they need to be accessed with
get(key)(e.g.model.meta.get('something')). - For describing nullable types you can use the
null*()helpers -nullString(),nullInt(),nullFloat(),nullBool(),nullArray(),nullObject().
Example:
const model = new DynamicModel({
name: "" // or nullString() if nullable
age: 0, // or nullInt() if nullable
totalSpent: -0, // or nullFloat() if nullable
active: false, // or nullBool() if nullable
Roles: [], // or nullArray() if nullable; maps to "Roles" in the DB/JSON but the prop would be accessible via "model.roles"
meta: {}, // or nullObject() if nullable
})
Context
new (parentCtx?: Context, key?: any, value?: any)
Context creates a new empty Go context.Context.
This is usually used as part of some Go transitive bindings.
Example:
const blank = new Context()
// with single key-value pair
const base = new Context(null, "a", 123)
console.log(base.value("a")) // 123
// extend with additional key-value pair
const sub = new Context(base, "b", 456)
console.log(sub.value("a")) // 123
console.log(sub.value("b")) // 456
Is a context.Context.
Record
new (collection?: core.Collection, data?: { [key:string]: any })
Record model class.
const collection = $app.findCollectionByNameOrId("article")
const record = new Record(collection, {
title: "Lorem ipsum"
})
// or set field values after the initialization
record.set("description", "...")
Is a core.Record.
Collection
new (data?: Partial<Collection>)
Collection model class.
const collection = new Collection({
type: "base",
name: "article",
listRule: "@request.auth.id != '' || status = 'public'",
viewRule: "@request.auth.id != '' || status = 'public'",
deleteRule: "@request.auth.id != ''",
fields: [
{
name: "title",
type: "text",
required: true,
min: 6,
max: 100,
},
{
name: "description",
type: "text",
},
]
})
Is a core.Collection.
FieldsList
new (data?: Partial<core.FieldsList>)
FieldsList model class, usually used to define the Collection.fields.
Is a core.FieldsList.
Field
new (data?: Partial<core.Field>)
Field model class, usually used as part of the FieldsList model.
Is a core.Field.
NumberField
new (data?: Partial<core.NumberField>)
Is a core.NumberField.
BoolField
new (data?: Partial<core.BoolField>)
Is a core.BoolField.
TextField
new (data?: Partial<core.TextField>)
Is a core.TextField.
URLField
new (data?: Partial<core.URLField>)
Is a core.URLField.
EmailField
new (data?: Partial<core.EmailField>)
Is a core.EmailField.
EditorField
new (data?: Partial<core.EditorField>)
Is a core.EditorField.
PasswordField
new (data?: Partial<core.PasswordField>)
Is a core.PasswordField.
DateField
new (data?: Partial<core.DateField>)
Is a core.DateField.
AutodateField
new (data?: Partial<core.AutodateField>)
Is a core.AutodateField.
JSONField
new (data?: Partial<core.JSONField>)
Is a core.JSONField.
RelationField
new (data?: Partial<core.RelationField>)
Is a core.RelationField.
SelectField
new (data?: Partial<core.SelectField>)
Is a core.SelectField.
FileField
new (data?: Partial<core.FileField>)
Is a core.FileField.
GeoPointField
new (data?: Partial<core.GeoPointField>)
Is a core.GeoPointField.
MailerMessage
new (message?: Partial<mailer.Message>)
MailerMessage defines a single email message.
const message = new MailerMessage({
from: {
address: $app.settings().meta.senderAddress,
name: $app.settings().meta.senderName,
},
to: [{address: "[email protected]"}],
subject: "YOUR_SUBJECT...",
html: "YOUR_HTML_BODY...",
})
$app.newMailClient().send(message)
Is a mailer.Message.
Command
new (cmd?: Partial<cobra.Command>)
Command defines a single console command.
Example:
const command = new Command({
use: "hello",
run: (cmd, args) => { console.log("Hello world!") },
})
$app.rootCmd.addCommand(command);
Is a cobra.Command.
RequestInfo
new (info?: Partial<core.RequestInfo>)
RequestInfo defines a single core.RequestInfo instance, usually used as part of various filter checks.
Example:
const authRecord = $app.findAuthRecordByEmail("users", "[email protected]")
const info = new RequestInfo({
auth: authRecord,
body: {"name": 123},
headers: {"x-token": "..."},
})
const record = $app.findFirstRecordByData("articles", "slug", "hello")
const canAccess = $app.canAccessRecord(record, info, "@request.auth.id != '' && @request.body.name = 123")
Is a core.RequestInfo.
Middleware
Middleware defines a single request middleware handler.
This class is usually used when you want to explicitly specify a priority to your custom route middleware.
Example:
routerUse(new Middleware((e) => {
console.log(e.request.url.path)
return e.next()
}, -10))
Timezone
new (name?: string)
Timezone returns the timezone location with the given name.
The name is expected to be a location name corresponding to a file in the IANA Time Zone database, such as "America/New_York".
If the name is "Local", LoadLocation returns Local.
If the name is "", invalid or "UTC", returns UTC.
The constructor is equivalent to calling the Go time.LoadLocation(name) method.
Example:
const zone = new Timezone("America/New_York")
$app.cron().setTimezone(zone)
Is a time.Location.
DateTime
new (date?: string, defaultParseInLocation?: string)
DateTime defines a single DateTime type instance. The returned date is always represented in UTC.
Example:
const dt0 = new DateTime() // now
// full datetime string
const dt1 = new DateTime('2023-07-01 00:00:00.000Z')
// datetime string with default "parse in" timezone location
//
// similar to new DateTime('2023-07-01 00:00:00 +01:00') or new DateTime('2023-07-01 00:00:00 +02:00')
// but accounts for the daylight saving time (DST)
const dt2 = new DateTime('2023-07-01 00:00:00', 'Europe/Amsterdam')
Is a types.DateTime.
ValidationError
new (code?: string, message?: string)
ValidationError defines a single formatted data validation error, usually used as part of an error response.
new ValidationError("invalid_title", "Title is not valid")
Is a ozzo_validation.Error.
Cookie
new (options?: Partial<http.Cookie>)
A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an HTTP response.
Example:
routerAdd("POST", "/example", (c) => {
c.setCookie(new Cookie({
name: "example_name",
value: "example_value",
path: "/",
domain: "example.com",
maxAge: 10,
secure: true,
httpOnly: true,
sameSite: 3,
}))
return c.redirect(200, "/");
})
Is a http.Cookie.
SubscriptionMessage
new (options?: Partial<subscriptions.Message>)
SubscriptionMessage defines a realtime subscription payload.
Example:
onRealtimeConnectRequest((e) => {
e.client.send(new SubscriptionMessage({
name: "example",
data: '{"greeting": "Hello world"}'
}))
})
Is a subscriptions.Message.
AppleClientSecretCreateForm
new (app: CoreApp)
Is a forms.AppleClientSecretCreate.
RecordUpsertForm
new (app: CoreApp, record: core.Record)
Is a forms.RecordUpsert.
TestEmailSendForm
new (app: CoreApp)
Is a forms.TestEmailSend.
TestS3FilesystemForm
new (app: CoreApp)
Is a forms.TestS3Filesystem.
ApiError
new (status?: number, message?: string, data?: any)
Is a router.ApiError.
NotFoundError
new (message?: string, data?: any)
NotFounderor returns 404 ApiError.
Is a router.ApiError.
BadRequestError
new (message?: string, data?: any)
BadRequestError returns 400 ApiError.
Is a router.ApiError.
ForbiddenError
new (message?: string, data?: any)
ForbiddenError returns 403 ApiError.
Is a router.ApiError.
UnauthorizedError
new (message?: string, data?: any)
UnauthorizedError returns 401 ApiError.
Is a router.ApiError.
TooManyRequestsError
new (message?: string, data?: any)
TooManyRequestsError returns 429 ApiError.
Is a router.ApiError.
InternalServerError
new (message?: string, data?: any)
InternalServerError returns 429 ApiError.
Is a router.ApiError.
DOMException
AbortSignal
AbortController
process
Buffer
A small Node-style Buffer: bytes with utf8, base64, base64url, hex and latin1 conversions.
Is a Uint8Array.
Hooks
Each hook takes a handler that gets the event; call e.next() to go on to the next handler (and the action itself). Hooks marked with tags take collection names (or ids) after the handler, so the handler runs only for those.
| Hook | Event | |
|---|---|---|
onBackupCreate(handler) |
core.BackupEvent |
OnBackupCreate hook is triggered on each App.createBackup call. |
onBackupRestore(handler) |
core.BackupEvent |
OnBackupRestore hook is triggered before app backup restore (aka. App.restoreBackup call). |
onBatchRequest(handler) |
core.BatchRequestEvent |
OnBatchRequest hook is triggered on each API batch request. |
onBootstrap(handler) |
core.BootstrapEvent |
OnBootstrap hook is triggered when initializing the main application resources (db, app settings, etc). |
onBootstrapClear(handler) |
core.BootstrapEvent |
OnBootstrapClear hook is triggered when clearing the main application resources (db connections, cron, logger, etc.) |
onCollectionAfterCreateError(handler, ...tags) |
core.CollectionErrorEvent |
OnCollectionAfterCreateError is a Collection proxy model hook of OnModelAfterCreateError. |
onCollectionAfterCreateSuccess(handler, ...tags) |
core.CollectionEvent |
OnCollectionAfterCreateSuccess is a Collection proxy model hook of OnModelAfterCreateSuccess. |
onCollectionAfterDeleteError(handler, ...tags) |
core.CollectionErrorEvent |
OnCollectionAfterDeleteError is a Collection proxy model hook of OnModelAfterDeleteError. |
onCollectionAfterDeleteSuccess(handler, ...tags) |
core.CollectionEvent |
OnCollectionAfterDeleteSuccess is a Collection proxy model hook of OnModelAfterDeleteSuccess. |
onCollectionAfterUpdateError(handler, ...tags) |
core.CollectionErrorEvent |
OnCollectionAfterUpdateError is a Collection proxy model hook of OnModelAfterUpdateError. |
onCollectionAfterUpdateSuccess(handler, ...tags) |
core.CollectionEvent |
OnCollectionAfterUpdateSuccess is a Collection proxy model hook of OnModelAfterUpdateSuccess. |
onCollectionCreate(handler, ...tags) |
core.CollectionEvent |
OnCollectionCreate is a Collection proxy model hook of OnModelCreate. |
onCollectionCreateExecute(handler, ...tags) |
core.CollectionEvent |
OnCollectionCreateExecute is a Collection proxy model hook of OnModelCreateExecute. |
onCollectionCreateRequest(handler) |
core.CollectionRequestEvent |
OnCollectionCreateRequest hook is triggered on each API Collection create request. |
onCollectionDelete(handler, ...tags) |
core.CollectionEvent |
OnCollectionDelete is a Collection proxy model hook of OnModelDelete. |
onCollectionDeleteExecute(handler, ...tags) |
core.CollectionEvent |
OnCollectionDeleteExecute is a Collection proxy model hook of OnModelDeleteExecute. |
onCollectionDeleteRequest(handler) |
core.CollectionRequestEvent |
OnCollectionDeleteRequest hook is triggered on each API Collection delete request. |
onCollectionUpdate(handler, ...tags) |
core.CollectionEvent |
OnCollectionUpdate is a Collection proxy model hook of OnModelUpdate. |
onCollectionUpdateExecute(handler, ...tags) |
core.CollectionEvent |
OnCollectionUpdateExecute is a Collection proxy model hook of OnModelUpdateExecute. |
onCollectionUpdateRequest(handler) |
core.CollectionRequestEvent |
OnCollectionUpdateRequest hook is triggered on each API Collection update request. |
onCollectionValidate(handler, ...tags) |
core.CollectionEvent |
OnCollectionValidate is a Collection proxy model hook of OnModelValidate. |
onCollectionViewRequest(handler) |
core.CollectionRequestEvent |
OnCollectionViewRequest hook is triggered on each API Collection view request. |
onCollectionsImportRequest(handler) |
core.CollectionsImportRequestEvent |
OnCollectionsBeforeImportRequest hook is triggered on each API collections import request. |
onCollectionsListRequest(handler) |
core.CollectionsListRequestEvent |
OnCollectionsListRequest hook is triggered on each API Collections list request. |
onFileDownloadRequest(handler, ...tags) |
core.FileDownloadRequestEvent |
OnFileDownloadRequest hook is triggered before each API File download request. |
onFileTokenRequest(handler, ...tags) |
core.FileTokenRequestEvent |
OnFileBeforeTokenRequest hook is triggered on each auth file token API request. |
onFilesystemCreate(handler) |
core.FilesystemCreateEvent |
PocketOne: OnFilesystemCreate hook is triggered every time app.NewFilesystem() or app.NewBackupsFilesystem() creates a filesystem, before the default one. A handler may supply its own (see FilesystemCreateEvent). Plugins may trigger it for their own kinds too. |
onMailerRecordAuthAlertSend(handler, ...tags) |
core.MailerRecordEvent |
OnMailerRecordAuthAlertSend hook is triggered when sending a new device login auth alert email, allowing you to intercept and customize the email message that is being sent. |
onMailerRecordEmailChangeSend(handler, ...tags) |
core.MailerRecordEvent |
OnMailerRecordEmailChangeSend hook is triggered when sending a confirmation new address email to an auth record, allowing you to intercept and customize the email message that is being sent. |
onMailerRecordOTPSend(handler, ...tags) |
core.MailerRecordEvent |
OnMailerRecordOTPSend hook is triggered when sending an OTP email to an auth record, allowing you to intercept and customize the email message that is being sent. |
onMailerRecordPasswordResetSend(handler, ...tags) |
core.MailerRecordEvent |
OnMailerBeforeRecordResetPasswordSend hook is triggered when sending a password reset email to an auth record, allowing you to intercept and customize the email message that is being sent. |
onMailerRecordVerificationSend(handler, ...tags) |
core.MailerRecordEvent |
OnMailerBeforeRecordVerificationSend hook is triggered when sending a verification email to an auth record, allowing you to intercept and customize the email message that is being sent. |
onMailerSend(handler) |
core.MailerEvent |
OnMailerSend hook is triggered every time when a new email is being sent using the [App.NewMailClient()] instance. |
onModelAfterCreateError(handler, ...tags) |
core.ModelErrorEvent |
OnModelAfterCreateError is triggered after each failed Model DB create persistence. |
onModelAfterCreateSuccess(handler, ...tags) |
core.ModelEvent |
OnModelAfterCreateSuccess is triggered after each successful Model DB create persistence. |
onModelAfterDeleteError(handler, ...tags) |
core.ModelErrorEvent |
OnModelAfterDeleteError is triggered after each failed Model DB delete persistence. |
onModelAfterDeleteSuccess(handler, ...tags) |
core.ModelEvent |
OnModelAfterDeleteSuccess is triggered after each successful Model DB delete persistence. |
onModelAfterUpdateError(handler, ...tags) |
core.ModelErrorEvent |
OnModelAfterUpdateError is triggered after each failed Model DB update persistence. |
onModelAfterUpdateSuccess(handler, ...tags) |
core.ModelEvent |
OnModelAfterUpdateSuccess is triggered after each successful Model DB update persistence. |
onModelCreate(handler, ...tags) |
core.ModelEvent |
OnModelCreate is triggered every time when a new model is being created (e.g. triggered by App.Save()). |
onModelCreateExecute(handler, ...tags) |
core.ModelEvent |
OnModelCreateExecute is triggered after successful Model validation and right before the model INSERT DB statement execution. |
onModelDelete(handler, ...tags) |
core.ModelEvent |
OnModelDelete is triggered every time when a new model is being deleted (e.g. triggered by App.Delete()). |
onModelDeleteExecute(handler, ...tags) |
core.ModelEvent |
OnModelUpdateExecute is triggered right before the model DELETE DB statement execution. |
onModelUpdate(handler, ...tags) |
core.ModelEvent |
OnModelUpdate is triggered every time when a new model is being updated (e.g. triggered by App.Save()). |
onModelUpdateExecute(handler, ...tags) |
core.ModelEvent |
OnModelUpdateExecute is triggered after successful Model validation and right before the model UPDATE DB statement execution. |
onModelValidate(handler, ...tags) |
core.ModelEvent |
OnModelValidate is triggered every time when a model is being validated (e.g. triggered by App.Validate() or App.Save()). |
onRealtimeConnectRequest(handler) |
core.RealtimeConnectRequestEvent |
OnRealtimeConnectRequest hook is triggered when establishing the SSE client connection. |
onRealtimeMessageSend(handler) |
core.RealtimeMessageEvent |
OnRealtimeMessageSend hook is triggered when sending an SSE message to a client. |
onRealtimeSubscribeRequest(handler) |
core.RealtimeSubscribeRequestEvent |
OnRealtimeSubscribeRequest hook is triggered when updating the client subscriptions, allowing you to further validate and modify the submitted change. |
onRecordAfterCreateError(handler, ...tags) |
core.RecordErrorEvent |
OnRecordAfterCreateError is a Record proxy model hook of OnModelAfterCreateError. |
onRecordAfterCreateSuccess(handler, ...tags) |
core.RecordEvent |
OnRecordAfterCreateSuccess is a Record proxy model hook of OnModelAfterCreateSuccess. |
onRecordAfterDeleteError(handler, ...tags) |
core.RecordErrorEvent |
OnRecordAfterDeleteError is a Record proxy model hook of OnModelAfterDeleteError. |
onRecordAfterDeleteSuccess(handler, ...tags) |
core.RecordEvent |
OnRecordAfterDeleteSuccess is a Record proxy model hook of OnModelAfterDeleteSuccess. |
onRecordAfterUpdateError(handler, ...tags) |
core.RecordErrorEvent |
OnRecordAfterUpdateError is a Record proxy model hook of OnModelAfterUpdateError. |
onRecordAfterUpdateSuccess(handler, ...tags) |
core.RecordEvent |
OnRecordAfterUpdateSuccess is a Record proxy model hook of OnModelAfterUpdateSuccess. |
onRecordAuthRefreshRequest(handler, ...tags) |
core.RecordAuthRefreshRequestEvent |
OnRecordAuthRefreshRequest hook is triggered on each Record auth refresh API request (right before generating a new auth token). |
onRecordAuthRequest(handler, ...tags) |
core.RecordAuthRequestEvent |
OnRecordAuthRequest hook is triggered on each successful API record authentication request (sign-in, token refresh, etc.). |
onRecordAuthWithOAuth2Request(handler, ...tags) |
core.RecordAuthWithOAuth2RequestEvent |
OnRecordAuthWithOAuth2Request hook is triggered on each Record OAuth2 sign-in/sign-up API request (after token exchange and before external provider linking). |
onRecordAuthWithOTPRequest(handler, ...tags) |
core.RecordAuthWithOTPRequestEvent |
OnRecordAuthWithOTPRequest hook is triggered on each Record auth with OTP API request. |
onRecordAuthWithPasswordRequest(handler, ...tags) |
core.RecordAuthWithPasswordRequestEvent |
OnRecordAuthWithPasswordRequest hook is triggered on each Record auth with password API request. |
onRecordConfirmEmailChangeRequest(handler, ...tags) |
core.RecordConfirmEmailChangeRequestEvent |
OnRecordConfirmEmailChangeRequest hook is triggered on each Record confirm email change API request. |
onRecordConfirmPasswordResetRequest(handler, ...tags) |
core.RecordConfirmPasswordResetRequestEvent |
OnRecordConfirmPasswordResetRequest hook is triggered on each Record confirm password reset API request. |
onRecordConfirmVerificationRequest(handler, ...tags) |
core.RecordConfirmVerificationRequestEvent |
OnRecordConfirmVerificationRequest hook is triggered on each Record confirm verification API request. |
onRecordCreate(handler, ...tags) |
core.RecordEvent |
OnRecordCreate is a Record proxy model hook of OnModelCreate. |
onRecordCreateExecute(handler, ...tags) |
core.RecordEvent |
OnRecordCreateExecute is a Record proxy model hook of OnModelCreateExecute. |
onRecordCreateRequest(handler, ...tags) |
core.RecordRequestEvent |
OnRecordCreateRequest hook is triggered on each API Record create request. |
onRecordDelete(handler, ...tags) |
core.RecordEvent |
OnRecordDelete is a Record proxy model hook of OnModelDelete. |
onRecordDeleteExecute(handler, ...tags) |
core.RecordEvent |
OnRecordDeleteExecute is a Record proxy model hook of OnModelDeleteExecute. |
onRecordDeleteRequest(handler, ...tags) |
core.RecordRequestEvent |
OnRecordDeleteRequest hook is triggered on each API Record delete request. |
onRecordEnrich(handler, ...tags) |
core.RecordEnrichEvent |
OnRecordEnrich is triggered every time when a record is enriched (as part of the builtin Record responses, during realtime message seriazation, or when apis.enrichRecord is invoked). |
onRecordRequestEmailChangeRequest(handler, ...tags) |
core.RecordRequestEmailChangeRequestEvent |
OnRecordRequestEmailChangeRequest hook is triggered on each Record request email change API request. |
onRecordRequestOTPRequest(handler, ...tags) |
core.RecordCreateOTPRequestEvent |
OnRecordRequestOTPRequest hook is triggered on each Record request OTP API request. |
onRecordRequestPasswordResetRequest(handler, ...tags) |
core.RecordRequestPasswordResetRequestEvent |
OnRecordRequestPasswordResetRequest hook is triggered on each Record request password reset API request. |
onRecordRequestVerificationRequest(handler, ...tags) |
core.RecordRequestVerificationRequestEvent |
OnRecordRequestVerificationRequest hook is triggered on each Record request verification API request. |
onRecordUpdate(handler, ...tags) |
core.RecordEvent |
OnRecordUpdate is a Record proxy model hook of OnModelUpdate. |
onRecordUpdateExecute(handler, ...tags) |
core.RecordEvent |
OnRecordUpdateExecute is a Record proxy model hook of OnModelUpdateExecute. |
onRecordUpdateRequest(handler, ...tags) |
core.RecordRequestEvent |
OnRecordUpdateRequest hook is triggered on each API Record update request. |
onRecordValidate(handler, ...tags) |
core.RecordEvent |
OnRecordValidate is a Record proxy model hook of OnModelValidate. |
onRecordViewRequest(handler, ...tags) |
core.RecordRequestEvent |
OnRecordViewRequest hook is triggered on each API Record view request. |
onRecordsListRequest(handler, ...tags) |
core.RecordsListRequestEvent |
OnRecordsListRequest hook is triggered on each API Records list request. |
onSettingsListRequest(handler) |
core.SettingsListRequestEvent |
OnSettingsListRequest hook is triggered on each API Settings list request. |
onSettingsReload(handler) |
core.SettingsReloadEvent |
OnSettingsReload hook is triggered every time when the App.Settings() is being replaced with a new state. |
onSettingsUpdateRequest(handler) |
core.SettingsUpdateRequestEvent |
OnSettingsUpdateRequest hook is triggered on each API Settings update request. |
onTerminate(handler) |
core.TerminateEvent |
OnTerminate hook is triggered when the app is in the process of being terminated (ex. on SIGTERM signal). |
Types
CoreApp
excludeHooks<core.App>
PocketBase
extends excludeHooks<pocketbase.PocketBase>
FormData
| Member | Type | |
|---|---|---|
append() |
(key: string, value: any): void |
|
set() |
(key: string, value: any): void |
GoArgs
The arguments JS passes to Go function F: all of them, or all but the first when it is a context.Context
(the engine supplies that one).
F extends (ctx: infer C, ...rest: infer R) => any
AsyncOptions
Options for fn.asyncWith. @group PocketOne
| Member | Type | |
|---|---|---|
signal? |
AbortSignal | null |
Aborts the call: the promise rejects with signal.reason and the Go function's context is cancelled. |
DOMException
An error with a name, as in browsers: AbortSignal's reasons are DOMExceptions named "AbortError" (code 20)
and "TimeoutError" (code 23).
extends Error
| Member | Type | |
|---|---|---|
name |
string |
|
message |
string |
|
code |
number |
AbortEvent
The event an AbortSignal's listeners get. @group PocketOne
| Member | Type | |
|---|---|---|
type |
"abort" |
|
target |
AbortSignal |
|
currentTarget |
AbortSignal |
AbortSignal
Says when to stop, as in browsers: pass one to fn.asyncWith({ signal }, ...) (or an API that takes { signal }).
AbortSignal.timeout(ms) runs on a Go timer that keeps going after the request is answered, so background work
can bound its calls where setTimeout is refused. It counts against MaxTimers until it fires.
const signal = AbortSignal.any([AbortSignal.timeout(60_000), controller.signal])
| Member | Type | |
|---|---|---|
aborted |
boolean |
|
reason |
any |
|
onabort |
((this: AbortSignal, ev: AbortEvent) => any) | null |
|
throwIfAborted() |
(): void |
Throws reason if the signal has aborted. |
addEventListener() |
(type: "abort", listener: (this: AbortSignal, ev: AbortEvent) => any, options?: boolean | { once?: boolean }): void |
|
removeEventListener() |
(type: "abort", listener: (this: AbortSignal, ev: AbortEvent) => any): void |
AbortController
Makes a signal and aborts it, as in browsers.
const c = new AbortController()
cancelButtonPressed.then(() => c.abort())
await work.asyncWith({ signal: c.signal })
| Member | Type | |
|---|---|---|
signal |
AbortSignal |
|
abort() |
(reason?: any): void |
Aborts the signal with reason (an "AbortError" DOMException by default); later calls do nothing. |
Console
| Member | Type | |
|---|---|---|
log() |
(...data: any[]): void |
|
error() |
(...data: any[]): void |
|
warn() |
(...data: any[]): void |
|
info() |
(...data: any[]): void |
|
debug() |
(...data: any[]): void |
|
trace() |
(...data: any[]): void |
BufferEncoding
"utf8" | "utf-8" | "base64" | "base64url" | "hex" | "latin1" | "binary"
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.