core: Records and collections
import core "ganigeorgiev.com/pocketbase/pocketbase/core"
Part of core.
Types
AuthOrigin
type AuthOrigin struct {
*Record
}
AuthOrigin defines a Record proxy for working with the authOrigins collection.
NewAuthOrigin
func NewAuthOrigin(app App) *AuthOrigin
NewAuthOrigin instantiates and returns a new blank *AuthOrigin model.
Example usage:
origin := core.NewOrigin(app)
origin.SetRecordRef(user.Id)
origin.SetCollectionRef(user.Collection().Id)
origin.SetFingerprint("...")
app.Save(origin)
AuthOrigin.CollectionRef
func (m *AuthOrigin) CollectionRef() string
CollectionRef returns the "collectionRef" field value.
AuthOrigin.Created
func (m *AuthOrigin) Created() types.DateTime
Created returns the "created" record field value.
AuthOrigin.Fingerprint
func (m *AuthOrigin) Fingerprint() string
Fingerprint returns the "fingerprint" record field value.
AuthOrigin.PreValidate
func (m *AuthOrigin) PreValidate(app App) error
PreValidate implements the PreValidator interface and checks whether the proxy is properly loaded.
AuthOrigin.ProxyRecord
func (m *AuthOrigin) ProxyRecord() *Record
ProxyRecord returns the proxied Record model.
AuthOrigin.RecordRef
func (m *AuthOrigin) RecordRef() string
RecordRef returns the "recordRef" record field value.
AuthOrigin.SetCollectionRef
func (m *AuthOrigin) SetCollectionRef(collectionId string)
SetCollectionRef updates the "collectionRef" record field value.
AuthOrigin.SetFingerprint
func (m *AuthOrigin) SetFingerprint(fingerprint string)
SetFingerprint updates the "fingerprint" record field value.
AuthOrigin.SetProxyRecord
func (m *AuthOrigin) SetProxyRecord(record *Record)
SetProxyRecord loads the specified record model into the current proxy.
AuthOrigin.SetRecordRef
func (m *AuthOrigin) SetRecordRef(recordId string)
SetRecordRef updates the "recordRef" record field value.
AuthOrigin.Updated
func (m *AuthOrigin) Updated() types.DateTime
Updated returns the "updated" record field value.
BaseModel
type BaseModel struct {
// Id is the primary key of the model.
// It is usually autogenerated by the parent model implementation.
Id string `db:"id" json:"id" form:"id" xml:"id"`
// contains filtered or unexported fields
}
BaseModel defines a base struct that is intended to be embedded into other custom models.
BaseModel.IsNew
func (m *BaseModel) IsNew() bool
IsNew indicates what type of db query (insert or update) should be used with the model instance.
BaseModel.LastSavedPK
func (m *BaseModel) LastSavedPK() any
LastSavedPK returns the last saved primary key of the model.
Its value is updated to the latest PK value after MarkAsNotNew() or PostScan() calls.
BaseModel.MarkAsNew
func (m *BaseModel) MarkAsNew()
MarkAsNew clears the pk field and marks the current model as "new" (aka. forces m.IsNew() to be true).
BaseModel.MarkAsNotNew
func (m *BaseModel) MarkAsNotNew()
MarkAsNew set the pk field to the Id value and marks the current model as NOT "new" (aka. forces m.IsNew() to be false).
BaseModel.PK
func (m *BaseModel) PK() any
BaseModel.PostScan
func (m *BaseModel) PostScan() error
PostScan implements the dbx.PostScanner interface.
It is usually executed right after the model is populated with the db row values.
BaseRecordProxy
type BaseRecordProxy struct {
*Record
}
BaseRecordProxy implements the RecordProxy interface and it is intended to be used as embed to custom user provided Record proxy structs.
BaseRecordProxy.ProxyRecord
func (m *BaseRecordProxy) ProxyRecord() *Record
ProxyRecord returns the proxied Record model.
BaseRecordProxy.SetProxyRecord
func (m *BaseRecordProxy) SetProxyRecord(record *Record)
SetProxyRecord loads the specified record model into the current proxy.
Collection
type Collection struct {
// contains filtered or unexported fields
}
Collection defines the table, fields and various options related to a set of records.
NewAuthCollection
func NewAuthCollection(name string, optId ...string) *Collection
NewAuthCollection initializes and returns a new "auth" Collection model.
It also loads the minimal default configuration for the collection (eg. system fields, indexes, type specific options, etc.).
NewBaseCollection
func NewBaseCollection(name string, optId ...string) *Collection
NewBaseCollection initializes and returns a new "base" Collection model.
It also loads the minimal default configuration for the collection (eg. system fields, indexes, type specific options, etc.).
NewCollection
func NewCollection(typ, name string, optId ...string) *Collection
NewCollection initializes and returns a new Collection model with the specified type and name.
It also loads the minimal default configuration for the collection (eg. system fields, indexes, type specific options, etc.).
NewViewCollection
func NewViewCollection(name string, optId ...string) *Collection
NewViewCollection initializes and returns a new "view" Collection model.
It also loads the minimal default configuration for the collection (eg. system fields, indexes, type specific options, etc.).
Collection.AddIndex
func (m *Collection) AddIndex(name string, unique bool, columnsExpr string, optWhereExpr string)
AddIndex adds a new index into the current collection.
If the collection has an existing index matching the new name it will be replaced with the new one.
Collection.BaseFilesPath
func (m *Collection) BaseFilesPath() string
BaseFilesPath returns the storage dir path used by the collection.
Collection.DBExport
func (m *Collection) DBExport(app App) (map[string]any, error)
DBExport prepares and exports the current collection data for db persistence.
Collection.GetIndex
func (m *Collection) GetIndex(name string) string
GetIndex returns s single Collection index expression by its name.
Collection.IntegrityChecks
func (m *Collection) IntegrityChecks(enable bool)
IntegrityChecks toggles the current collection integrity checks (ex. checking references on delete).
Collection.IsAuth
func (m *Collection) IsAuth() bool
IsAuth checks if the current collection has "auth" type.
Collection.IsBase
func (m *Collection) IsBase() bool
IsBase checks if the current collection has "base" type.
Collection.IsView
func (m *Collection) IsView() bool
IsView checks if the current collection has "view" type.
Collection.MarshalJSON
func (m Collection) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface.
Note that non-type related fields are ignored from the serialization (ex. for "view" collections the "auth" fields are skipped).
Collection.PostScan
func (m *Collection) PostScan() error
PostScan implements the dbx.PostScanner interface to auto unmarshal the raw serialized options into the concrete type specific fields.
Collection.RemoveIndex
func (m *Collection) RemoveIndex(name string)
RemoveIndex removes a single index with the specified name from the current collection.
Collection.String
func (m Collection) String() string
String returns a string representation of the current collection.
Collection.TableName
func (m *Collection) TableName() string
TableName returns the Collection model SQL table name.
Collection.UnmarshalJSON
func (m *Collection) UnmarshalJSON(b []byte) error
UnmarshalJSON implements the json.Unmarshaler interface.
For new/"blank" Collection models it replaces the model with a factory instance and then unmarshal the provided data one on top of it.
ExternalAuth
type ExternalAuth struct {
*Record
}
ExternalAuth defines a Record proxy for working with the externalAuths collection.
NewExternalAuth
func NewExternalAuth(app App) *ExternalAuth
NewExternalAuth instantiates and returns a new blank *ExternalAuth model.
Example usage:
ea := core.NewExternalAuth(app)
ea.SetRecordRef(user.Id)
ea.SetCollectionRef(user.Collection().Id)
ea.SetProvider("google")
ea.SetProviderId("...")
app.Save(ea)
ExternalAuth.CollectionRef
func (m *ExternalAuth) CollectionRef() string
CollectionRef returns the "collectionRef" field value.
ExternalAuth.Created
func (m *ExternalAuth) Created() types.DateTime
Created returns the "created" record field value.
ExternalAuth.PreValidate
func (m *ExternalAuth) PreValidate(app App) error
PreValidate implements the PreValidator interface and checks whether the proxy is properly loaded.
ExternalAuth.Provider
func (m *ExternalAuth) Provider() string
Provider returns the "provider" record field value.
ExternalAuth.ProviderId
func (m *ExternalAuth) ProviderId() string
Provider returns the "providerId" record field value.
ExternalAuth.ProxyRecord
func (m *ExternalAuth) ProxyRecord() *Record
ProxyRecord returns the proxied Record model.
ExternalAuth.RecordRef
func (m *ExternalAuth) RecordRef() string
RecordRef returns the "recordRef" record field value.
ExternalAuth.SetCollectionRef
func (m *ExternalAuth) SetCollectionRef(collectionId string)
SetCollectionRef updates the "collectionRef" record field value.
ExternalAuth.SetProvider
func (m *ExternalAuth) SetProvider(provider string)
SetProvider updates the "provider" record field value.
ExternalAuth.SetProviderId
func (m *ExternalAuth) SetProviderId(providerId string)
SetProvider updates the "providerId" record field value.
ExternalAuth.SetProxyRecord
func (m *ExternalAuth) SetProxyRecord(record *Record)
SetProxyRecord loads the specified record model into the current proxy.
ExternalAuth.SetRecordRef
func (m *ExternalAuth) SetRecordRef(recordId string)
SetRecordRef updates the "recordRef" record field value.
ExternalAuth.Updated
func (m *ExternalAuth) Updated() types.DateTime
Updated returns the "updated" record field value.
Log
type Log struct {
BaseModel
Created types.DateTime `db:"created" json:"created"`
Data types.JSONMap[any] `db:"data" json:"data"`
Message string `db:"message" json:"message"`
Level int `db:"level" json:"level"`
}
Log.DBExport
func (l *Log) DBExport(app App) (map[string]any, error)
DBExport prepares and exports the current log model for db persistence.
It also truncates the log's message and data to ensure that it is under app.Settings().Logs.MaxDataSize.
Log.TableName
func (l *Log) TableName() string
LogsStatsItem
type LogsStatsItem struct {
Date types.DateTime `db:"date" json:"date"`
Total int `db:"total" json:"total"`
}
LogsStatsItem defines the total number of logs for a specific time period.
MFA
type MFA struct {
*Record
}
MFA defines a Record proxy for working with the mfas collection.
NewMFA
func NewMFA(app App) *MFA
NewMFA instantiates and returns a new blank *MFA model.
Example usage:
mfa := core.NewMFA(app)
mfa.SetRecordRef(user.Id)
mfa.SetCollectionRef(user.Collection().Id)
mfa.SetMethod(core.MFAMethodPassword)
app.Save(mfa)
MFA.CollectionRef
func (m *MFA) CollectionRef() string
CollectionRef returns the "collectionRef" field value.
MFA.Created
func (m *MFA) Created() types.DateTime
Created returns the "created" record field value.
MFA.HasExpired
func (m *MFA) HasExpired(maxElapsed time.Duration) bool
HasExpired checks if the mfa is expired, aka. whether it has been more than maxElapsed time since its creation.
MFA.Method
func (m *MFA) Method() string
Method returns the "method" record field value.
MFA.PreValidate
func (m *MFA) PreValidate(app App) error
PreValidate implements the PreValidator interface and checks whether the proxy is properly loaded.
MFA.ProxyRecord
func (m *MFA) ProxyRecord() *Record
ProxyRecord returns the proxied Record model.
MFA.RecordRef
func (m *MFA) RecordRef() string
RecordRef returns the "recordRef" record field value.
MFA.SetCollectionRef
func (m *MFA) SetCollectionRef(collectionId string)
SetCollectionRef updates the "collectionRef" record field value.
MFA.SetMethod
func (m *MFA) SetMethod(method string)
SetMethod updates the "method" record field value.
MFA.SetProxyRecord
func (m *MFA) SetProxyRecord(record *Record)
SetProxyRecord loads the specified record model into the current proxy.
MFA.SetRecordRef
func (m *MFA) SetRecordRef(recordId string)
SetRecordRef updates the "recordRef" record field value.
MFA.Updated
func (m *MFA) Updated() types.DateTime
Updated returns the "updated" record field value.
Model
type Model interface {
TableName() string
PK() any
LastSavedPK() any
IsNew() bool
MarkAsNew()
MarkAsNotNew()
}
Model defines an interface with common methods that all db models should have.
Note: for simplicity composite pk are not supported.
OTP
type OTP struct {
*Record
}
OTP defines a Record proxy for working with the otps collection.
NewOTP
func NewOTP(app App) *OTP
NewOTP instantiates and returns a new blank *OTP model.
Example usage:
otp := core.NewOTP(app)
otp.SetRecordRef(user.Id)
otp.SetCollectionRef(user.Collection().Id)
otp.SetPassword(security.RandomStringWithAlphabet(6, "1234567890"))
app.Save(otp)
OTP.CollectionRef
func (m *OTP) CollectionRef() string
CollectionRef returns the "collectionRef" field value.
OTP.Created
func (m *OTP) Created() types.DateTime
Created returns the "created" record field value.
OTP.HasExpired
func (m *OTP) HasExpired(maxElapsed time.Duration) bool
HasExpired checks if the otp is expired, aka. whether it has been more than maxElapsed time since its creation.
OTP.PreValidate
func (m *OTP) PreValidate(app App) error
PreValidate implements the PreValidator interface and checks whether the proxy is properly loaded.
OTP.ProxyRecord
func (m *OTP) ProxyRecord() *Record
ProxyRecord returns the proxied Record model.
OTP.RecordRef
func (m *OTP) RecordRef() string
RecordRef returns the "recordRef" record field value.
OTP.SentTo
func (m *OTP) SentTo() string
SentTo returns the "sentTo" record field value.
It could be any string value (email, phone, message app id, etc.) and usually is used as part of the auth flow to update the verified user state in case for example the sentTo value matches with the user record email.
OTP.SetCollectionRef
func (m *OTP) SetCollectionRef(collectionId string)
SetCollectionRef updates the "collectionRef" record field value.
OTP.SetProxyRecord
func (m *OTP) SetProxyRecord(record *Record)
SetProxyRecord loads the specified record model into the current proxy.
OTP.SetRecordRef
func (m *OTP) SetRecordRef(recordId string)
SetRecordRef updates the "recordRef" record field value.
OTP.SetSentTo
func (m *OTP) SetSentTo(val string)
SetSentTo updates the "sentTo" record field value.
OTP.Updated
func (m *OTP) Updated() types.DateTime
Updated returns the "updated" record field value.
Param
type Param struct {
BaseModel
Created types.DateTime `db:"created" json:"created"`
Updated types.DateTime `db:"updated" json:"updated"`
Value types.JSONRaw `db:"value" json:"value"`
}
Param.TableName
func (m *Param) TableName() string
Record
type Record struct {
BaseModel
// contains filtered or unexported fields
}
NewRecord
func NewRecord(collection *Collection) *Record
NewRecord initializes a new empty Record model.
Record.BaseFilesPath
func (m *Record) BaseFilesPath() string
BaseFilesPath returns the storage dir path used by the record.
Record.Clone
func (m *Record) Clone() *Record
Clone returns a shallow copy of the current record model with all of its collection and unknown fields data, expand and flags copied.
use [Record.Fresh()] instead if you want a copy with only the latest collection fields data and everything else reset to the defaults.
Record.Collection
func (m *Record) Collection() *Collection
Collection returns the Collection model associated with the current Record model.
NB! The returned collection is only for read purposes and it shouldn't be modified because it could have unintended side-effects on other Record models from the same collection.
Record.CustomData
func (m *Record) CustomData() map[string]any
CustomData returns a shallow copy ONLY of the custom record fields data, aka. fields that are neither defined by the collection, nor special system ones.
Note that custom fields prefixed with "@pbInternal" are always skipped.
Record.DBExport
func (m *Record) DBExport(app App) (map[string]any, error)
DBExport implements the DBExporter interface and returns a key-value map with the data to be persisted when saving the Record in the database.
Record.Email
func (m *Record) Email() string
Email returns the "email" record field value (usually available with Auth collections).
Record.EmailVisibility
func (m *Record) EmailVisibility() bool
Verified returns the "emailVisibility" record field value (usually available with Auth collections).
Record.Expand
func (m *Record) Expand() map[string]any
Expand returns a shallow copy of the current Record model expand data (if any).
Record.ExpandedAll
func (m *Record) ExpandedAll(relField string) []*Record
ExpandedAll retrieves a slice of relation Records from the already loaded expand data of the current model.
If the requested expand relation is single, this method normalizes the return result and will wrap the single model as a slice.
Returns nil slice if there is no such expand relation loaded.
Record.ExpandedOne
func (m *Record) ExpandedOne(relField string) *Record
ExpandedOne retrieves a single relation Record from the already loaded expand data of the current model.
If the requested expand relation is multiple, this method returns only first available Record from the expanded relation.
Returns nil if there is no such expand relation loaded.
Record.FieldsData
func (m *Record) FieldsData() map[string]any
FieldsData returns a shallow copy ONLY of the collection's fields record's data.
Record.FindFileFieldByFile
func (m *Record) FindFileFieldByFile(filename string) *FileField
FindFileFieldByFile returns the first file type field for which any of the record's data contains the provided filename.
Record.Fresh
func (m *Record) Fresh() *Record
Fresh returns a shallow copy of the current record model populated with its LATEST data state and everything else reset to the defaults (aka. no expand, no unknown fields and with default visibility flags).
Record.Get
func (m *Record) Get(key string) any
Get returns a normalized single record model data value for "key".
Record.GetBool
func (m *Record) GetBool(key string) bool
GetBool returns the data value for "key" as a bool.
Record.GetDateTime
func (m *Record) GetDateTime(key string) types.DateTime
GetDateTime returns the data value for "key" as a DateTime instance.
Record.GetFloat
func (m *Record) GetFloat(key string) float64
GetFloat returns the data value for "key" as a float64.
Record.GetGeoPoint
func (m *Record) GetGeoPoint(key string) types.GeoPoint
GetGeoPoint returns the data value for "key" as a GeoPoint instance.
Record.GetInt
func (m *Record) GetInt(key string) int
GetInt returns the data value for "key" as an int.
Record.GetInt64
func (m *Record) GetInt64(key string) int64
GetInt64 returns the data value for "key" as an int64.
Record.GetRaw
func (m *Record) GetRaw(key string) any
Record.GetString
func (m *Record) GetString(key string) string
GetString returns the data value for "key" as a string.
Record.GetStringSlice
func (m *Record) GetStringSlice(key string) []string
GetStringSlice returns the data value for "key" as a slice of non-zero unique strings.
Record.GetUnsavedFiles
func (m *Record) GetUnsavedFiles(key string) []*filesystem.File
GetUnsavedFiles returns the uploaded files for the provided "file" field key, (aka. the current *filesystem.File values) so that you can apply further validations or modifications (including changing the file name or content before persisting).
Example:
files := record.GetUnsavedFiles("documents")
for _, f := range files {
f.Name = "doc_" + f.Name // add a prefix to each file name
}
app.Save(record) // the files are pointers so the applied changes will transparently reflect on the record value
Record.GetUploadedFiles
func (m *Record) GetUploadedFiles(key string) []*filesystem.File
Deprecated: replaced with GetUnsavedFiles.
Record.Hide
func (record *Record) Hide(fieldNames ...string) *Record
Hide hides the specified fields from the public safe serialization of the record.
Record.HookTags
func (m *Record) HookTags() []string
HookTags returns the hook tags associated with the current record.
Record.IgnoreEmailVisibility
func (m *Record) IgnoreEmailVisibility(state bool) *Record
IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check.
Record.IgnoreUnchangedFields
func (m *Record) IgnoreUnchangedFields(state bool) *Record
IgnoreUnchangedFields toggles the flag to ignore the unchanged fields from the DB export for the UPDATE SQL query.
This could be used if you want to save only the record fields that you've changed without overwrite other untouched fields in case of concurrent update.
Note that the fields change comparison is based on the current fields against m.Original() (aka. if you have performed save on the same Record instance multiple times you may have to refetch it, so that m.Original() could reflect the last saved change).
Record.IsSuperuser
func (m *Record) IsSuperuser() bool
IsSuperuser returns whether the current record is a superuser, aka. whether the record is from the _superusers collection.
Record.Load
func (m *Record) Load(data map[string]any)
Load bulk loads the provided data into the current Record model.
Record.MarshalJSON
func (m Record) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface.
Only the data exported by `PublicExport()` will be serialized.
Record.MergeExpand
func (m *Record) MergeExpand(expand map[string]any)
MergeExpand merges recursively the provided expand data into the current model's expand (if any).
Note that if an expanded prop with the same key is a slice (old or new expand) then both old and new records will be merged into a new slice (aka. a :merge: [b,c] => [a,b,c]). Otherwise the "old" expanded record will be replace with the "new" one (aka. a :merge: aNew => aNew).
Record.NewAuthToken
func (m *Record) NewAuthToken() (string, error)
NewAuthToken generates and returns a new record authentication token.
Record.NewEmailChangeToken
func (m *Record) NewEmailChangeToken(newEmail string) (string, error)
NewEmailChangeToken generates and returns a new auth record change email request token.
Record.NewFileToken
func (m *Record) NewFileToken() (string, error)
NewFileToken generates and returns a new record private file access token.
Record.NewPasswordResetToken
func (m *Record) NewPasswordResetToken() (string, error)
NewPasswordResetToken generates and returns a new auth record password reset request token.
Record.NewStaticAuthToken
func (m *Record) NewStaticAuthToken(duration time.Duration) (string, error)
NewStaticAuthToken generates and returns a new static record authentication token.
Static auth tokens are similar to the regular auth tokens, but are non-refreshable and support custom duration.
Zero or negative duration will fallback to the duration from the auth collection settings.
Record.NewVerificationToken
func (m *Record) NewVerificationToken() (string, error)
NewVerificationToken generates and returns a new record verification token.
Record.Original
func (m *Record) Original() *Record
Original returns a shallow copy of the current record model populated with its ORIGINAL db data state (aka. right after PostScan()) and everything else reset to the defaults.
If record was created using NewRecord() the original will be always a blank record (until PostScan() is invoked).
Record.PostScan
func (m *Record) PostScan() error
PostScan implements the dbx.PostScanner interface.
It essentially refreshes/updates the current Record original state as if the model was fetched from the databases for the first time.
Or in other words, it means that m.Original().FieldsData() will have the same values as m.Record().FieldsData().
Record.PublicExport
func (record *Record) PublicExport() map[string]any
PublicExport exports only the record fields that are safe to be public.
To export unknown data fields you need to set record.WithCustomData(true).
For auth records, to force the export of the email field you need to set record.IgnoreEmailVisibility(true).
Record.RefreshTokenKey
func (m *Record) RefreshTokenKey()
RefreshTokenKey generates and sets a new random auth record "tokenKey".
Record.ReplaceModifiers
func (m *Record) ReplaceModifiers(data map[string]any) map[string]any
ReplaceModifiers returns a new map with applied modifier values based on the current record and the specified data.
The resolved modifier keys will be removed.
Multiple modifiers will be applied one after another, while reusing the previous base key value result (ex. 1; -5; +2 => -2).
Note that because Go doesn't guaranteed the iteration order of maps, we would explicitly apply shorter keys first for a more consistent and reproducible behavior.
Example usage:
newData := record.ReplaceModifiers(data)
// record: {"field": 10}
// data: {"field+": 5}
// result: {"field": 15}
Record.Set
func (m *Record) Set(key string, value any)
Set sets the provided key-value data pair into the current Record model.
If the record collection has field with name matching the provided "key", the value will be further normalized according to the field setter(s).
Record.SetEmail
func (m *Record) SetEmail(email string)
SetEmail sets the "email" record field value (usually available with Auth collections).
Record.SetEmailVisibility
func (m *Record) SetEmailVisibility(visible bool)
SetEmailVisibility sets the "emailVisibility" record field value (usually available with Auth collections).
Record.SetExpand
func (m *Record) SetExpand(expand map[string]any)
SetExpand replaces the current Record's expand with the provided expand arg data (shallow copied).
Record.SetIfFieldExists
func (m *Record) SetIfFieldExists(key string, value any) Field
SetIfFieldExists sets the provided key-value data pair into the current Record model ONLY if key is existing Collection field name/modifier.
This method does nothing if key is not a known Collection field name/modifier.
On success returns the matched Field, otherwise - nil.
To set any key-value, including custom/unknown fields, use the Record.Set method.
Record.SetPassword
func (m *Record) SetPassword(password string)
SetPassword sets the "password" record field value (usually available with Auth collections).
Record.SetRandomPassword
func (m *Record) SetRandomPassword() string
SetRandomPassword sets the "password" auth record field to a random autogenerated value.
The autogenerated password is ~30 characters and it is set directly as hash, aka. the field plain password value validators (length, pattern, etc.) are ignored (this is usually used as part of the auto created OTP or OAuth2 user flows).
Record.SetRaw
func (m *Record) SetRaw(key string, value any)
Set sets the provided key-value data pair into the current Record model directly as it is WITHOUT NORMALIZATIONS.
See also Record.Set.
Record.SetTokenKey
func (m *Record) SetTokenKey(key string)
SetTokenKey sets the "tokenKey" record field value (usually available with Auth collections).
Record.SetVerified
func (m *Record) SetVerified(verified bool)
SetVerified sets the "verified" record field value (usually available with Auth collections).
Record.TableName
func (m *Record) TableName() string
TableName returns the table name associated with the current Record model.
Record.TokenKey
func (m *Record) TokenKey() string
TokenKey returns the "tokenKey" record field value (usually available with Auth collections).
Record.Unhide
func (record *Record) Unhide(fieldNames ...string) *Record
Unhide forces to unhide the specified fields from the public safe serialization of the record (even when the collection field itself is marked as hidden).
Record.UnmarshalJSON
func (m *Record) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface.
Record.UnmarshalJSONField
func (m *Record) UnmarshalJSONField(key string, result any) error
Retrieves the "key" json field value and unmarshals it into "result".
Example
result := struct {
FirstName string `json:"first_name"`
}{}
err := m.UnmarshalJSONField("my_field_name", &result)
Record.ValidatePassword
func (m *Record) ValidatePassword(password string) bool
ValidatePassword validates a plain password against the "password" record field.
Returns false if the password is incorrect.
Record.Verified
func (m *Record) Verified() bool
Verified returns the "verified" record field value (usually available with Auth collections).
Record.WithCustomData
func (m *Record) WithCustomData(state bool) *Record
WithCustomData toggles the export/serialization of custom data fields (false by default).
RecordFieldResolver
type RecordFieldResolver struct {
// contains filtered or unexported fields
}
RecordFieldResolver defines a custom search resolver struct for managing Record model search fields.
Usually used together with `search.Provider`. Example:
resolver := resolvers.NewRecordFieldResolver(
app,
myCollection,
&models.RequestInfo{...},
true,
)
provider := search.NewProvider(resolver)
...
NewRecordFieldResolver
func NewRecordFieldResolver(
app App,
baseCollection *Collection,
requestInfo *RequestInfo,
allowHiddenFields bool,
) *RecordFieldResolver
NewRecordFieldResolver creates and initializes a new `RecordFieldResolver`.
RecordFieldResolver.AllowHiddenFields
func (r *RecordFieldResolver) AllowHiddenFields() bool
AllowHiddenFields returns whether the current resolver allows filtering hidden fields.
RecordFieldResolver.AllowedFields
func (r *RecordFieldResolver) AllowedFields() []string
AllowedFields returns a copy of the resolver's allowed fields.
RecordFieldResolver.Resolve
func (r *RecordFieldResolver) Resolve(fieldName string) (*search.ResolverResult, error)
Resolve implements `search.FieldResolver` interface.
Example of some resolvable fieldName formats:
id
someSelect.each
project.screen.status
screen.project_via_prototype.name
@request.context
@request.method
@request.query.filter
@request.headers.x_token
@request.auth.someRelation.name
@request.body.someRelation.name
@request.body.someField
@request.body.someSelect:each
@request.body.someField:isset
@collection.product.name
RecordFieldResolver.SetAllowHiddenFields
func (r *RecordFieldResolver) SetAllowHiddenFields(allowHiddenFields bool)
SetAllowHiddenFields enables or disables hidden fields filtering.
RecordFieldResolver.SetAllowedFields
func (r *RecordFieldResolver) SetAllowedFields(newAllowedFields []string)
SetAllowedFields replaces the resolver's allowed fields with the new ones.
RecordFieldResolver.UpdateQuery
func (r *RecordFieldResolver) UpdateQuery(query *dbx.SelectQuery) error
@todo think of a better a way how to call it automatically after BuildExpr
UpdateQuery implements `search.FieldResolver` interface.
Conditionally updates the provided search query based on the resolved fields (eg. dynamically joining relations).
RecordInterceptor
type RecordInterceptor interface {
// Interceptor is invoked when a specific record action occurs
// allowing you to perform extra validations and normalization
// (ex. uploading or deleting files).
//
// Note that users must call actionFunc() manually if they want to
// execute the specific record action.
Intercept(
app App,
record *Record,
actionName string,
actionFunc func() error,
) error
}
RecordInterceptor defines a field interface for reacting to various Record related operations (create, delete, validate, etc.).
RecordProxy
type RecordProxy interface {
// ProxyRecord returns the proxied Record model.
ProxyRecord() *Record
// SetProxyRecord loads the specified record model into the current proxy.
SetProxyRecord(record *Record)
}
RecordProxy defines an interface for a Record proxy/project model, aka. custom model struct that acts on behalve the proxied Record to allow for example typed getter/setters for the Record fields.
To implement the interface it is usually enough to embed the BaseRecordProxy struct.
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.