models

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

internal/models/json_map.go

Index

Constants

View Source
const (
	ConnectionAuthNone   = "none"
	ConnectionAuthBearer = "bearer" // Authorization: Bearer <secret>
	ConnectionAuthHeader = "header" // <HeaderName>: <secret>
)

Connection auth types.

View Source
const (
	StatusDraft     = "draft"
	StatusPublished = "published"
)

Item statuses in draft-and-publish collections.

View Source
const (
	ProposalPending  = "pending"
	ProposalApproved = "approved"
	ProposalRejected = "rejected"
	// ProposalFailed: approved, but the change could not be applied (the
	// data no longer validates, the item is gone…).
	ProposalFailed = "failed"
)

Proposal statuses.

View Source
const (
	ProposalCreate = "create"
	ProposalUpdate = "update"
	ProposalDelete = "delete"
)

Proposal actions.

View Source
const (
	RevisionEntityItem      = "item"      // EntityID is the item ID
	RevisionEntitySingleton = "singleton" // EntityID is the singleton (single type) ID
)

Revision entity types.

View Source
const (
	RevisionCreate    = "create"
	RevisionUpdate    = "update"
	RevisionPublish   = "publish"
	RevisionUnpublish = "unpublish"
	RevisionDelete    = "delete"
	RevisionRestore   = "restore"
	// RevisionBaseline holds an entry's content from before history was
	// recorded: it is written just before the first change of an entry
	// that has no revisions yet.
	RevisionBaseline = "baseline"
)

Revision actions.

View Source
const (
	ActorUser   = "user"
	ActorToken  = "token"
	ActorAgent  = "agent"
	ActorSystem = "system"
)

Revision actor kinds.

View Source
const (
	WebhookFormatJSON  = "json"  // the full event as JSON
	WebhookFormatSlack = "slack" // {"text": "..."}, for Slack (and compatible) incoming webhooks
)

Webhook formats.

View Source
const APITokenPrefix = "ght_"

APITokenPrefix starts every API token, so tokens are recognizable in headers, logs and secret scanners, and never confused with JWTs.

View Source
const ConnectionProposalPrefix = "app:"

ConnectionProposalPrefix starts the Collection of call proposals ("app:github"): no collection name has a colon.

View Source
const MinPasswordLength = 6

MinPasswordLength is the minimum accepted length for a plain-text password.

View Source
const ProposalCall = "call"

ProposalCall is the action of a proposal to call a connected app's tool.

Variables

View Source
var ReservedAttributeNames = []string{"id", "createdAt", "updatedAt", "publishedAt"}

ReservedAttributeNames are system fields included in every item response; attributes cannot use them.

View Source
var ReservedDraftAttributeNames = []string{"status"}

ReservedDraftAttributeNames are also reserved when draft and publish is on.

View Source
var ReservedLocaleAttributeNames = []string{"locale", "locales"}

ReservedLocaleAttributeNames are also reserved in types with localized attributes.

View Source
var WebhookEvents = []string{"item:created", "item:updated", "item:deleted", "item:published", "item:unpublished", "singleton:updated", "singleton:deleted"}

WebhookEvents are the events a webhook can subscribe to ("*" means all).

Functions

func APITime added in v0.4.0

func APITime(t time.Time) time.Time

APITime normalizes a timestamp for responses: UTC, microsecond precision (what PostgreSQL and MySQL store), so a value reads the same whether it comes from memory right after a write or from the database later.

func APITokenResponse added in v0.5.0

func APITokenResponse(t APIToken) map[string]any

APITokenResponse is the JSON shape of a token (never its secret).

func HasLocalized added in v0.5.0

func HasLocalized(attrs []Attribute) bool

HasLocalized reports whether any attribute is localized.

func ItemResponse added in v0.4.0

func ItemResponse(ct Collection, item Item, data JSONMap) map[string]any

ItemResponse is the JSON shape of an item in every API response: its attributes at the top level, plus id, createdAt and updatedAt, and publishedAt and status for draft-and-publish collections. data is the (possibly relation-populated) item data; nil means item.Data.

func JSONBytes added in v0.5.0

func JSONBytes(value any) ([]byte, error)

JSONBytes returns the raw JSON of a scanned column: drivers return JSON columns as []byte (PostgreSQL, MySQL) or string (SQLite text columns).

func JSONDBDataType added in v0.5.0

func JSONDBDataType(db *gorm.DB, _ *schema.Field) string

JSONDBDataType implements GormDBDataType for JSON-valued types. MySQL has no JSONB, so JSON columns are created as JSON there; other databases keep the type given in the field's tag (json or jsonb).

func LocalizedNames added in v0.5.0

func LocalizedNames(attrs []Attribute) map[string]bool

LocalizedNames returns the names of the localized attributes.

func LocalizedResponse added in v0.5.0

func LocalizedResponse(out map[string]any, attrs []Attribute, translations JSONMap, locale, defaultLocale string) map[string]any

LocalizedResponse adds "locale" and "locales" to an entry's response when its type has localized attributes.

func MediaResponse added in v0.4.0

func MediaResponse(m Media, url string) map[string]any

MediaResponse is the JSON shape of a media file in API responses.

func SingleItemResponse added in v0.4.0

func SingleItemResponse(item SingleItem, data JSONMap) map[string]any

SingleItemResponse is the JSON shape of a singleton's content: its attributes at the top level plus id, createdAt and updatedAt. data is the (possibly relation-populated) data; nil means item.Data.

func ToUint

func ToUint(value any) uint

func ToUintSlice added in v0.4.0

func ToUintSlice(value any) []uint

ToUintSlice converts a stored many-to-many value to IDs. It accepts the shapes found before and after a JSON round-trip ([]uint right after validation, []any of float64 once read back). Invalid entries are dropped.

func TranslatedLocales added in v0.5.0

func TranslatedLocales(translations JSONMap) []string

TranslatedLocales lists the locales with at least one value, sorted.

func TranslatedLocalesOf added in v0.5.0

func TranslatedLocalesOf(attrs []Attribute, translations JSONMap) []string

TranslatedLocalesOf lists the locales with a value for at least one of the localized attributes (values kept for attributes that are no longer localized do not count), sorted.

func Translation added in v0.5.0

func Translation(translations JSONMap, locale string) map[string]any

Translation returns the stored values of one locale (nil if none).

func ValidLocaleCode added in v0.5.0

func ValidLocaleCode(code string) bool

ValidLocaleCode reports whether code looks like a BCP 47 language tag.

func ValidateCollectionSchema

func ValidateCollectionSchema(ct Collection) error

ValidateCollectionSchema is the single source of truth for validating a collection's structure. It correctly uses the TypeRegistry for all type checks.

func ValidateComponentSchema

func ValidateComponentSchema(cmp Component) error

ValidateComponentSchema ensures the component schema is valid.

func ValidateSingleItemValues

func ValidateSingleItemValues(st Singleton, itemData map[string]any) error

ValidateSingleItemValues validates a single item's data against the SingleType's schema (attributes).

func ValidateSingletonSchema

func ValidateSingletonSchema(singleton Singleton) error

ValidateSingletonSchema ensures the structure of a singleton is valid.

func ValidateSingletonValues

func ValidateSingletonValues(singleton Singleton, data map[string]any) error

ValidateSingletonValues checks if provided data conforms to the singleton's schema.

func ValidateUser

func ValidateUser(user User) error

func ValidateUserRole

func ValidateUserRole(role UserRole) error

ValidateUserRole validates the user role data

func ValidateUserUpdates

func ValidateUserUpdates(updates map[string]interface{}) error

ValidateUserUpdates validates updates to a user's fields

func WebhookResponse added in v0.5.0

func WebhookResponse(w Webhook) map[string]any

WebhookResponse is the JSON shape of a webhook. Header values and the secret are never returned (they often hold credentials).

func WithNestedCollector added in v0.5.0

func WithNestedCollector(tx *gorm.DB, c *NestedCreated) *gorm.DB

WithNestedCollector returns tx with c attached: items that validation creates for relations given as objects are appended to c.

Types

type APIToken added in v0.5.0

type APIToken struct {
	gorm.Model
	ID          uint       `json:"id"`
	Name        string     `json:"name"`
	Description string     `json:"description"`
	Role        string     `json:"role"`                         // viewer, editor or admin
	Hash        string     `json:"-" gorm:"uniqueIndex;size:64"` // hex SHA-256 of the secret
	Prefix      string     `json:"prefix"`                       // first characters, to recognize it
	CreatedBy   string     `json:"createdBy"`                    //
	ExpiresAt   *time.Time `json:"expiresAt"`                    // nil: never
	LastUsedAt  *time.Time `json:"lastUsedAt"`                   // updated at most once a minute
	RevokedAt   *time.Time `json:"revokedAt" gorm:"index"`       //
}

APIToken is a long-lived key for front-ends, CI and integrations. Only a SHA-256 hash of the secret is stored; the secret is shown once, at creation. A token acts with the permissions of its role.

func (APIToken) Active added in v0.5.0

func (t APIToken) Active(now time.Time) bool

Active reports whether the token can still be used at t.

type Attribute

type Attribute struct {
	gorm.Model

	// Basic fields
	Name         string   `json:"name"`
	Type         string   `json:"type"` // e.g., "text", "int", "bool", "date", "richtext", "enum", "relation", "component"
	Required     bool     `json:"required"`
	Unique       bool     `json:"unique,omitempty"`
	Options      []string `gorm:"type:json;serializer:json" json:"options,omitempty"`
	Min          *int     `json:"min,omitempty"`
	Max          *int     `json:"max,omitempty"`
	Pattern      string   `json:"pattern,omitempty"`
	CustomErrors JSONMap  `gorm:"type:json" json:"custom_errors,omitempty"`

	// Relationship-specific fields
	Target       string `json:"target,omitempty"`     // Target collection for relationships, or component name
	Relation     string `json:"relation,omitempty"`   // e.g., "oneToOne", "oneToMany", "manyToMany", for relationships
	ComponentRef string `json:"component,omitempty"`  // If Type="component", which component is referenced
	Repeatable   bool   `json:"repeatable,omitempty"` // Type="component": the value is a list of components

	// Media-specific fields
	Multiple     bool     `json:"multiple,omitempty"`                                       // Type="media": a list of files
	AllowedTypes []string `gorm:"type:json;serializer:json" json:"allowed_types,omitempty"` // Type="media": MIME patterns, e.g. "image/*"

	// Localized attributes have a value per locale (see Item.Translations).
	// Relations cannot be localized. Component attributes do not use it.
	Localized bool `json:"localized,omitempty" gorm:"not null;default:false"`

	// Foreign keys (an attribute can belong to either a Collection, a SingleType, or a Component)
	CollectionID *uint       `json:"collection_id,omitempty"`
	Collection   *Collection `json:"-" gorm:"constraint:OnDelete:CASCADE;"`

	SingletonID *uint      `json:"single_type_id,omitempty"`
	Singleton   *Singleton `json:"-" gorm:"constraint:OnDelete:CASCADE;"`

	ComponentID *uint      `json:"component_id,omitempty"`
	Component   *Component `json:"-" gorm:"constraint:OnDelete:CASCADE;"`
}

Attribute defines the structure for fields in a collection, single type, or component.

type BaseAttribute

type BaseAttribute struct {
	gorm.Model
	// Basic fields
	Name         string   `json:"name"`
	Type         string   `json:"type"`
	Required     bool     `json:"required"`
	Unique       bool     `json:"unique,omitempty"`
	Options      []string `gorm:"type:json;serializer:json" json:"options,omitempty"`
	Min          *int     `json:"min,omitempty"`
	Max          *int     `json:"max,omitempty"`
	Pattern      string   `json:"pattern,omitempty"`
	CustomErrors JSONMap  `gorm:"type:json" json:"custom_errors,omitempty"`
	// Relationship-specific fields
	Target   string `json:"target,omitempty"`   // Target collection name for relationships
	Relation string `json:"relation,omitempty"` // e.g., "oneToOne", "oneToMany"

	// Component-specific fields
	ComponentRef string `json:"component,omitempty"`  // Name of the referenced component if Type="component"
	Repeatable   bool   `json:"repeatable,omitempty"` // Type="component": the value is a list of components

	// Media-specific fields
	Multiple     bool     `json:"multiple,omitempty"`                                       // Type="media": a list of files
	AllowedTypes []string `gorm:"type:json;serializer:json" json:"allowed_types,omitempty"` // Type="media": MIME patterns, e.g. "image/*"
}

Attribute defines the structure for fields in a collection, single type, or component.

func (BaseAttribute) ToAttribute added in v0.4.0

func (b BaseAttribute) ToAttribute() Attribute

ToAttribute converts a component attribute so it can go through the same value validation as collection attributes.

type Collection

type Collection struct {
	gorm.Model
	ID          uint   `json:"id"`
	Name        string `json:"name" gorm:"uniqueIndex;size:191"`
	Kind        string `json:"kind" gorm:"type:varchar(50);not null"`
	Description string `json:"description"`
	// DraftAndPublish enables the draft/publish workflow: items start as
	// drafts and only published items are visible to readers.
	DraftAndPublish bool        `json:"draft_and_publish" gorm:"not null;default:false"`
	Attributes      []Attribute `json:"attributes" gorm:"constraint:OnDelete:CASCADE;"`

	// DraftAndPublishSet records whether the input named the option, so an
	// update that leaves it out keeps the current value.
	DraftAndPublishSet bool `json:"-" gorm:"-"`
}

func ParseCollectionInput

func ParseCollectionInput(input map[string]any) (Collection, error)

func (*Collection) GetAttributeType

func (c *Collection) GetAttributeType(attributeName string) (string, error)

GetAttributeType correctly identifies an attribute as a "attribute" or "relationship".

func (*Collection) ToFlattenedMap

func (c *Collection) ToFlattenedMap() map[string]any

ToFlattenedMap converts the Collection into a flat map structure

type Component

type Component struct {
	gorm.Model
	ID          uint                 `json:"id"`
	Name        string               `json:"name" gorm:"uniqueIndex;size:191"`
	Description string               `json:"description"`
	Attributes  []ComponentAttribute `json:"attributes" gorm:"foreignKey:ComponentID;constraint:OnDelete:CASCADE;"`
}

func ParseComponentInput

func ParseComponentInput(input map[string]any) (Component, error)

type ComponentAttribute

type ComponentAttribute struct {
	BaseAttribute
	ComponentID uint `json:"-"`
}

type Connection added in v0.7.0

type Connection struct {
	ID    uint   `json:"id" gorm:"primaryKey"`
	Name  string `json:"name" gorm:"size:64;uniqueIndex;not null"`
	Label string `json:"label" gorm:"size:191"`
	// Preset is the catalog entry it was made from ("github", "zapier"),
	// empty for a custom server.
	Preset string `json:"preset,omitempty" gorm:"size:64"`
	// URL of the MCP server (Streamable HTTP transport).
	URL        string `json:"url" gorm:"type:text;not null"`
	AuthType   string `json:"authType" gorm:"size:16;not null"`
	HeaderName string `json:"headerName,omitempty" gorm:"size:191"`
	// Secret is the token, encrypted (see pkg/secrets). Never returned.
	Secret string `json:"-" gorm:"type:text"`
	// Tools is the server's tool list, as of ToolsUpdatedAt.
	Tools          ConnectionTools `json:"tools" gorm:"type:json;serializer:json"`
	ToolsUpdatedAt *time.Time      `json:"toolsUpdatedAt,omitempty"`
	// LastError is the error of the last refresh, empty when it worked.
	LastError string    `json:"lastError,omitempty" gorm:"type:text"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

Connection is another service agents can use: a remote MCP server (GitHub, Zapier, your own…) whose tools become agent tools named "<connection>.<tool>".

func (Connection) HasSecret added in v0.7.0

func (c Connection) HasSecret() bool

HasSecret reports whether a token is stored.

func (Connection) Tool added in v0.7.0

func (c Connection) Tool(name string) (ConnectionTool, bool)

Tool returns the connection's tool of that name.

func (*Connection) Validate added in v0.7.0

func (c *Connection) Validate() error

Validate checks the connection's settings (not its secret).

type ConnectionTool added in v0.7.0

type ConnectionTool struct {
	Name        string  `json:"name"`
	Title       string  `json:"title,omitempty"`
	Description string  `json:"description,omitempty"`
	InputSchema JSONMap `json:"inputSchema,omitempty"`
	// ReadOnly: the server says the tool changes nothing. Other tools
	// "write": they need approval unless the agent says otherwise.
	ReadOnly    bool `json:"readOnly"`
	Destructive bool `json:"destructive,omitempty"`
}

ConnectionTool is a tool a connected server offers.

type ConnectionTools added in v0.7.0

type ConnectionTools []ConnectionTool

ConnectionTools is a connection's tool list.

type Item

type Item struct {
	gorm.Model
	ID           uint    `json:"id"`
	CollectionID uint    `json:"collection"`
	Data         JSONMap `json:"data" gorm:"type:json"`
	// PublishedAt is set when the item is published. It is only meaningful
	// for collections with DraftAndPublish; nil means draft.
	PublishedAt *time.Time `json:"publishedAt" gorm:"index"`
	// Translations holds the values of localized attributes in the other
	// locales: {"fr": {"title": "…"}}. Data holds the default locale.
	Translations JSONMap `json:"translations,omitempty" gorm:"type:json"`
}

func (Item) Status added in v0.4.0

func (i Item) Status() string

Status returns StatusPublished or StatusDraft.

type JSONMap

type JSONMap map[string]interface{}

JSONMap is a custom type that implements driver.Valuer and sql.Scanner

func LocalizeData added in v0.5.0

func LocalizeData(attrs []Attribute, data, translations JSONMap, locale, defaultLocale string, fallback bool) JSONMap

LocalizeData returns data as seen in locale: localized attributes take their value in that locale; with fallback, a missing value falls back to the default locale's, otherwise it is left out. The default locale (or "") returns data unchanged.

func ValidateItemUpdate added in v0.4.0

func ValidateItemUpdate(ct Collection, itemData map[string]any, tx *gorm.DB, itemID uint) (JSONMap, error)

ValidateItemUpdate is ValidateItemValues for an existing item: unique attributes may keep the item's own current values.

func ValidateItemValues

func ValidateItemValues(ct Collection, itemData map[string]any, tx *gorm.DB) (JSONMap, error)

ValidateItemValues validates item data, creates nested relations, and returns the processed data. It MUST be called within a database transaction.

func (JSONMap) GormDBDataType added in v0.5.0

func (JSONMap) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType makes JSONMap columns JSON on MySQL.

func (*JSONMap) Scan

func (j *JSONMap) Scan(value interface{}) error

Scan implements the sql.Scanner interface, converting a JSON string from the database into a JSONMap. internal/models/json_map.go

func (JSONMap) Value

func (j JSONMap) Value() (driver.Value, error)

Value implements the driver.Valuer interface, converting the JSONMap to a JSON string for storage. It returns a string: MySQL refuses binary strings in JSON columns.

type Locale added in v0.5.0

type Locale struct {
	ID        uint      `json:"id" gorm:"primaryKey"`
	Code      string    `json:"code" gorm:"size:35;not null;uniqueIndex"`
	Name      string    `json:"name" gorm:"size:191"`
	IsDefault bool      `json:"isDefault" gorm:"not null;default:false"`
	CreatedAt time.Time `json:"createdAt"`
}

Locale is a content locale. Exactly one is the default: entries' main data is in it, and other locales are stored as translations.

type Media added in v0.4.0

type Media struct {
	gorm.Model
	ID         uint   `json:"id"`
	Name       string `json:"name"`                          // original file name
	Key        string `json:"-" gorm:"uniqueIndex;size:255"` // path in the store
	Driver     string `json:"-"`                             // store that holds it
	MimeType   string `json:"mime" gorm:"index"`             // detected from the content
	Size       int64  `json:"size"`                          // bytes
	Width      *int   `json:"width"`                         // images only
	Height     *int   `json:"height"`                        // images only
	Hash       string `json:"hash" gorm:"index"`             // SHA-256 of the content
	Alt        string `json:"alt"`                           // alternative text
	Caption    string `json:"caption"`                       //
	UploadedBy string `json:"uploadedBy" gorm:"index"`       // username
}

Media is an uploaded file. Its content lives in the media store (local directory or S3 bucket) under Key; this row holds its metadata.

type NestedCreated added in v0.5.0

type NestedCreated struct {
	Items []NestedItem
}

NestedCreated collects the items validation creates, so the caller can record them (history, events).

type NestedItem added in v0.5.0

type NestedItem struct {
	Item       *Item
	Collection Collection
}

NestedItem is an item created while validating a relation given as an object (see ValidateItemValues).

type Proposal added in v0.6.0

type Proposal struct {
	ID         uint    `json:"id" gorm:"primaryKey"`
	AgentName  string  `json:"agentName" gorm:"size:191;index"`
	AgentRunID *uint   `json:"agentRunId,omitempty" gorm:"index"`
	Action     string  `json:"action" gorm:"size:16;not null"`
	Collection string  `json:"collection" gorm:"size:191;not null;index"`
	ItemID     *uint   `json:"itemId,omitempty" gorm:"index"`
	Locale     string  `json:"locale,omitempty" gorm:"size:35"`
	Data       JSONMap `json:"data" gorm:"type:json"`
	// Reason is the agent's explanation, when it gave one.
	Reason string `json:"reason,omitempty" gorm:"type:text"`
	// BaseVersion is the item's latest revision when proposed (0: none),
	// to tell whether it changed since.
	BaseVersion uint       `json:"baseVersion"`
	Status      string     `json:"status" gorm:"size:16;not null;index"`
	ReviewedBy  string     `json:"reviewedBy,omitempty" gorm:"size:191"`
	ReviewNote  string     `json:"reviewNote,omitempty" gorm:"type:text"`
	Error       string     `json:"error,omitempty" gorm:"type:text"`
	CreatedAt   time.Time  `json:"createdAt" gorm:"index"`
	DecidedAt   *time.Time `json:"decidedAt,omitempty"`
	// Stale is set in lists of pending proposals: the item changed since.
	Stale bool `json:"stale,omitempty" gorm:"-"`
}

Proposal is a content change an agent asked for, applied only once an editor approves it (agents with require_approval).

type Revision added in v0.5.0

type Revision struct {
	ID         uint    `json:"id" gorm:"primaryKey"`
	EntityType string  `json:"entityType" gorm:"size:16;not null;uniqueIndex:idx_revisions_entity_version,priority:1"`
	EntityID   uint    `json:"entityId" gorm:"not null;uniqueIndex:idx_revisions_entity_version,priority:2"`
	Version    uint    `json:"version" gorm:"not null;uniqueIndex:idx_revisions_entity_version,priority:3"`
	TypeName   string  `json:"typeName" gorm:"size:191;index"` // collection or singleton name
	Action     string  `json:"action" gorm:"size:16;not null"`
	Status     string  `json:"status,omitempty" gorm:"size:16"` // draft or published (draft-and-publish collections)
	Data       JSONMap `json:"data" gorm:"type:json"`
	// Translations are the entry's localized values in other locales.
	Translations JSONMap `json:"translations,omitempty" gorm:"type:json"`
	ActorKind    string  `json:"actorKind" gorm:"size:16;not null"`
	ActorName    string  `json:"actorName" gorm:"size:191"`
	AgentRunID   *uint   `json:"agentRunId,omitempty" gorm:"index"`
	// RestoredFrom is the version a restore copied.
	RestoredFrom *uint     `json:"restoredFrom,omitempty"`
	CreatedAt    time.Time `json:"createdAt" gorm:"index"`
}

Revision is a snapshot of an entry (a collection item or a singleton's content) after one change. Versions count from 1 per entry. Data is the stored data after the change; for a delete, the data the entry had.

type SingleItem

type SingleItem struct {
	gorm.Model
	SingleTypeID uint      `json:"single_type_id" gorm:"uniqueIndex"`
	SingleType   Singleton `json:"-" gorm:"constraint:OnDelete:CASCADE;foreignKey:SingleTypeID;references:ID"`
	Data         JSONMap   `json:"data" gorm:"type:json"`
	// Translations: see Item.Translations.
	Translations JSONMap `json:"translations,omitempty" gorm:"type:json"`
}

type Singleton

type Singleton struct {
	gorm.Model
	ID          uint        `json:"id"`
	Name        string      `json:"name" gorm:"uniqueIndex;size:191"`
	Description string      `json:"description"`
	Attributes  []Attribute `json:"attributes" gorm:"constraint:OnDelete:CASCADE;"`
}

Singleton represents a content structure that has only one instance. e.g., a homepage, site settings, or a header.

func ParseSingletonInput

func ParseSingletonInput(input map[string]any) (Singleton, error)

ParseSingletonInput transforms a generic map input into a Singleton struct.

type User

type User struct {
	gorm.Model
	Username        string    `json:"username" gorm:"uniqueIndex;size:191"` // Unique username with length limit for MySQL compatibility
	Email           string    `json:"email" gorm:"uniqueIndex;size:191"`    // Unique email with length limit for MySQL compatibility
	Password        string    `json:"-"`                                    // Hashed password (never serialized)
	UserRoleID      int       `json:"-"`                                    // Foreign key reference (not exposed in JSON)
	Role            UserRole  `json:"role" gorm:"foreignKey:UserRoleID"`    // Associated role
	Slug            string    `json:"slug" gorm:"uniqueIndex;size:191"`     // Unique slug for the user
	ProfileImage    string    `json:"profile_image"`                        // URL to the user's profile image
	CoverImage      *string   `json:"cover_image"`                          // URL to the user's cover image (optional)
	Bio             string    `json:"bio"`                                  // Short biography
	Website         string    `json:"website"`                              // Personal or professional website
	Location        string    `json:"location"`                             // User's location
	Facebook        string    `json:"facebook"`                             // Facebook username or handle
	Twitter         string    `json:"twitter"`                              // Twitter handle
	MetaTitle       *string   `json:"meta_title"`                           // SEO meta title (optional)
	MetaDescription *string   `json:"meta_description"`                     // SEO meta description (optional)
	URL             string    `json:"url"`                                  // Full URL to the user's profile
	CreatedAt       time.Time `json:"created_at,omitempty"`                 // Auto-managed timestamp
	// SSOProvider is the identity provider the account signs in with
	// ("google"), and SSOSubject its ID there; empty for password accounts.
	SSOProvider string `json:"ssoProvider,omitempty" gorm:"size:32;index:idx_users_sso,priority:1"`
	SSOSubject  string `json:"-" gorm:"size:191;index:idx_users_sso,priority:2"`
}

User represents a user in the system with extended profile information.

type UserRole

type UserRole struct {
	ID          uint    `json:"id"`
	Name        string  `json:"name"`                                   // Role name (e.g., admin, editor, viewer)
	Description string  `json:"description"`                            // Role description
	Permissions JSONMap `json:"permissions" gorm:"type:jsonb;not null"` // Permissions associated with the role (JSON on MySQL)
}

UserRole defines the role of a user

type Webhook added in v0.5.0

type Webhook struct {
	gorm.Model
	ID          uint              `json:"id"`
	Name        string            `json:"name"`
	URL         string            `json:"url"`
	Events      []string          `json:"events" gorm:"type:json;serializer:json"`      // empty or "*": all
	Collections []string          `json:"collections" gorm:"type:json;serializer:json"` // empty: all
	Format      string            `json:"format"`                                       // json | slack
	Headers     map[string]string `json:"-" gorm:"type:json;serializer:json"`           // sent with each delivery
	Secret      string            `json:"-"`                                            // HMAC signing key
	Enabled     bool              `json:"enabled" gorm:"not null"`                      // no DB default: GORM would override false on create

	LastStatus     int        `json:"lastStatus"`
	LastError      string     `json:"lastError"`
	LastDeliveryAt *time.Time `json:"lastDeliveryAt"`
}

Webhook sends content events to an external URL: an integration such as Slack or Zapier, or a static-site rebuild hook.

func (Webhook) Matches added in v0.5.0

func (w Webhook) Matches(event, collection string) bool

Matches reports whether the webhook wants event on collection. Only the WebhookEvents are delivered: "all events" never includes internal ones such as schema changes.

type WebhookDelivery added in v0.5.0

type WebhookDelivery struct {
	ID         uint      `json:"id" gorm:"primaryKey"`
	WebhookID  uint      `json:"webhookId" gorm:"index"`
	DeliveryID string    `json:"deliveryId" gorm:"index"` // same for every attempt of one event
	Event      string    `json:"event"`
	Collection string    `json:"collection"`
	ItemID     uint      `json:"itemId"`
	Attempt    int       `json:"attempt"`
	StatusCode int       `json:"statusCode"` // 0 when no response was received
	Error      string    `json:"error"`
	DurationMs int64     `json:"durationMs"`
	CreatedAt  time.Time `json:"createdAt"`
}

WebhookDelivery records one delivery attempt.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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