models

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 17 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 (
	StatusDraft     = "draft"
	StatusPublished = "published"
)

Item statuses in draft-and-publish collections.

View Source
const MinPasswordLength = 6

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

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.

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 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 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 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

Types

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/*"

	// 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"`
	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"`
	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 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"`
}

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 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) 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.

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"`    // 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 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"`
}

type Singleton

type Singleton struct {
	gorm.Model
	ID          uint        `json:"id"`
	Name        string      `json:"name" gorm:"uniqueIndex"`
	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"`              // 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
}

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;default:'[]';not null"` // Use 'jsonb' for PostgreSQL // Permissions associated with the role
}

UserRole defines the role of a user

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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