readysite / website / internal / content / content.go
12.1 KB
content.go
// Package content provides the unified interface for content management.
// It re-exports types and functions from sub-packages to provide a clean API
// for controllers while hiding implementation details.
//
// Sub-packages:
//   - schema: Field types and schema parsing
//   - validate: Document and input validation
//   - rules: Rule expression parsing and authorization
//   - query: API filter parsing, expansion, and views
//   - api: OpenAPI spec generation and middleware
//   - render: Template functions and page rendering
//   - seed: Database seeding
package content

import (
	"net/http"

	"github.com/readysite/readysite/website/internal/content/api"
	"github.com/readysite/readysite/website/internal/content/query"
	"github.com/readysite/readysite/website/internal/content/render"
	"github.com/readysite/readysite/website/internal/content/rules"
	"github.com/readysite/readysite/website/internal/content/schema"
	"github.com/readysite/readysite/website/internal/content/seed"
	"github.com/readysite/readysite/website/internal/content/validate"
	"github.com/readysite/readysite/website/models"
)

// =============================================================================
// Schema Types and Functions (from schema/)
// =============================================================================

// Field types constants
const (
	Text     = schema.Text
	Number   = schema.Number
	Bool     = schema.Bool
	Date     = schema.Date
	Email    = schema.Email
	URL      = schema.URL
	Select   = schema.Select
	Relation = schema.Relation
	File     = schema.File
	JSON     = schema.JSON
	GeoPoint = schema.GeoPoint
	Editor   = schema.Editor
	Autodate = schema.Autodate
)

// Field represents a field definition in a collection schema.
type Field = schema.Field

// GetFields parses the schema from a collection.
var GetFields = schema.GetFields

// SetFields sets the schema on a collection.
var SetFields = schema.SetFields

// GetField returns a field by name from a collection.
var GetField = schema.GetField

// =============================================================================
// Validation Functions (from validate/)
// =============================================================================

// ValidationError represents a field validation error.
type ValidationError = validate.ValidationError

// ValidationErrors is a collection of validation errors.
type ValidationErrors = validate.ValidationErrors

// ValidateDocument validates document data against a collection's schema.
var ValidateDocument = validate.Document

// ValidateDocumentJSON validates document data from a JSON string.
var ValidateDocumentJSON = validate.DocumentJSON

// ProcessFieldModifiers processes field modifiers like field+ and field-.
var ProcessFieldModifiers = validate.ProcessFieldModifiers

// ProcessAutodate processes autodate fields, setting them to current time.
var ProcessAutodate = validate.ProcessAutodate

// ValidateEmail validates an email address format.
var ValidateEmail = validate.Email

// ValidateSlug checks if a slug is valid for use as an ID.
var ValidateSlug = validate.Slug

// ValidateSlugAvailable checks if a slug is available for a given resource type.
var ValidateSlugAvailable = validate.SlugAvailable

// ValidateTitle validates a title field.
var ValidateTitle = validate.Title

// ValidateDescription validates a description field.
var ValidateDescription = validate.Description

// ValidateHTML validates HTML content.
var ValidateHTML = validate.HTML

// ValidateName validates a name field.
var ValidateName = validate.Name

// ValidateSchema validates a collection schema JSON.
var ValidateSchema = validate.Schema

// ValidatePageInput validates all page input fields.
var ValidatePageInput = validate.PageInput

// ValidateCollectionInput validates all collection input fields.
var ValidateCollectionInput = validate.CollectionInput

// ValidateUpload validates an uploaded file.
var ValidateUpload = validate.Upload

// ValidatePath validates a file path.
var ValidatePath = validate.Path

// SanitizeFilename sanitizes a filename for safe storage.
var SanitizeFilename = validate.SanitizeFilename

// DetectMimeType detects MIME type from file content.
var DetectMimeType = validate.DetectMimeType

// ParseFormData converts HTTP form data to a map based on collection schema fields.
var ParseFormData = validate.ParseFormData

// CheckSlugAvailable checks if a slug is available for a given resource type.
var CheckSlugAvailable = validate.SlugAvailable

// Validation limits
const (
	MaxTitleLength       = validate.MaxTitleLength
	MaxDescriptionLength = validate.MaxDescriptionLength
	MaxHTMLLength        = validate.MaxHTMLLength
	MaxNameLength        = validate.MaxNameLength
	MaxSchemaLength      = validate.MaxSchemaLength
	MaxEmailLength       = validate.MaxEmailLength
	MaxFileSize          = validate.MaxFileSize
)

// =============================================================================
// Rules and Authorization (from rules/)
// =============================================================================

// RuleType represents the type of rule.
type RuleType = rules.RuleType

// Rule type constants
const (
	RuleTypeLocked     = rules.RuleTypeLocked
	RuleTypePublic     = rules.RuleTypePublic
	RuleTypeExpression = rules.RuleTypeExpression
)

// Context provides request context for rule evaluation.
type RuleContext = rules.Context

// Context is an alias for RuleContext (backward compatibility).
type Context = rules.Context

// NewRuleContext creates a Context from an HTTP request.
var NewRuleContext = rules.NewContext

// NewContext is an alias for NewRuleContext (backward compatibility).
var NewContext = rules.NewContext

// ParseRuleType determines the type of rule from the rule string.
var ParseRuleType = rules.ParseRuleType

// EvaluateRule evaluates a rule expression against context and record data.
var EvaluateRule = rules.Evaluate

// Evaluate is an alias for EvaluateRule (backward compatibility).
var Evaluate = rules.Evaluate

// RuleToSQLFilter converts a rule expression to a SQL WHERE clause.
var RuleToSQLFilter = rules.ToSQLFilter

// AuthResult represents the result of an authorization check.
type AuthResult = rules.AuthResult

// Authorizer handles authorization checks for collection operations.
type Authorizer = rules.Authorizer

// NewAuthorizer creates an Authorizer from a request and collection.
var NewAuthorizer = rules.NewAuthorizer

// =============================================================================
// Query and Filter Functions (from query/)
// =============================================================================

// APIFilterResult contains the parsed WHERE clause and parameters.
type APIFilterResult = query.APIFilterResult

// ParseFilter parses a filter expression and returns a parameterized WHERE clause.
var ParseFilter = query.ParseFilter

// ParseAPIFilter is an alias for ParseFilter (backward compatibility).
var ParseAPIFilter = query.ParseFilter

// ParseSort parses a sort expression and returns an ORDER BY clause.
var ParseSort = query.ParseSort

// FilterFields filters a map to only include the specified fields.
var FilterFields = query.FilterFields

// ParseFields parses a comma-separated fields parameter.
var ParseFields = query.ParseFields

// ParseExpand parses a comma-separated expand parameter.
var ParseExpand = query.ParseExpand

// MatchesFilter evaluates an APIFilterResult filter against a record in memory.
var MatchesFilter = query.MatchesFilter

// MatchesAPIFilter is an alias for MatchesFilter (backward compatibility).
var MatchesAPIFilter = query.MatchesFilter

// DocumentToRecord converts a Document to a flat map for API response.
var DocumentToRecord = query.DocumentToRecord

// ParseDocumentData parses a document's JSON data into a map.
var ParseDocumentData = query.ParseDocumentData

// RelationExpander expands relation fields in API responses.
type RelationExpander = query.RelationExpander

// NewExpander creates a new RelationExpander.
var NewExpander = query.NewExpander

// NewRelationExpander is an alias for NewExpander (backward compatibility).
var NewRelationExpander = query.NewExpander

// ExpandRecordSimple is a convenience function that expands a single record.
var ExpandRecordSimple = query.ExpandRecordSimple

// ViewRecord represents a single record in a view result.
type ViewRecord = query.ViewRecord

// ValidateViewQuery validates a view query string.
var ValidateViewQuery = query.ValidateQuery

// ExecuteView executes a view collection's query and returns results.
var ExecuteView = query.ExecuteView

// ExecuteViewSingle executes a view and returns a single record by ID.
var ExecuteViewSingle = query.ExecuteViewSingle

// DeriveViewSchema derives a schema from a view's base collection.
var DeriveViewSchema = query.DeriveSchema

// =============================================================================
// API Functions (from api/)
// =============================================================================

// OpenAPISpec represents an OpenAPI 3.0 specification.
type OpenAPISpec = api.OpenAPISpec

// GenerateOpenAPISpec generates an OpenAPI specification for the API.
var GenerateOpenAPISpec = api.GenerateSpec

// GenerateSpec is an alias for GenerateOpenAPISpec (backward compatibility).
var GenerateSpec = api.GenerateSpec

// SetCORSHeaders sets CORS headers on the response.
var SetCORSHeaders = api.SetCORSHeaders

// CheckRateLimit checks if a request is within rate limits.
var CheckRateLimit = api.CheckRateLimit

// CheckCollectionRateLimit checks rate limiting for a collection.
var CheckCollectionRateLimit = api.CheckCollectionRateLimit

// =============================================================================
// Render Functions (from render/)
// =============================================================================

// RenderPage renders a page's HTML content with template functions.
var RenderPage = render.RenderPage

// FindPageByPath finds a page by its full URL path.
var FindPageByPath = render.FindByPath

// FindByPath is an alias for FindPageByPath (backward compatibility).
var FindByPath = render.FindByPath

// AllTemplateFuncs returns all template functions.
var AllTemplateFuncs = render.AllFuncs

// AllFuncs is an alias for AllTemplateFuncs (backward compatibility).
var AllFuncs = render.AllFuncs

// TemplateFuncs returns template functions for page rendering.
var TemplateFuncs = render.Funcs

// Template function wrappers for direct use
var (
	Documents      = render.Documents
	Document       = render.Document
	Collection     = render.Collection
	Page           = render.Page
	Pages          = render.Pages
	PublishedPages = render.PublishedPages
	Partial        = render.Partial
	Partials       = render.Partials
	SiteName       = render.SiteName
	SiteDescription = render.SiteDescription
)

// RequestContext provides safe access to HTTP request data in templates.
type RequestContext = render.RequestContext

// NewRequestContext creates a sandboxed request context for templates.
var NewRequestContext = render.NewRequestContext

// =============================================================================
// Seeding Functions (from seed/)
// =============================================================================

// SeedAll runs all seeding functions and migrations.
var SeedAll = seed.All

// SeedDefaultPages seeds the default pages.
var SeedDefaultPages = seed.DefaultPages

// SeedCollections seeds default collections and sample data.
var SeedCollections = seed.Collections

// SeedBlogPages seeds the blog example pages.
var SeedBlogPages = seed.BlogPages

// SeedFiles seeds example files.
var SeedFiles = seed.Files

// SeedMigrations runs one-time data migrations.
var SeedMigrations = seed.Migrations

// =============================================================================
// Helper function that wraps NewAuthorizer for cleaner API
// =============================================================================

// Authorize creates an Authorizer from a request and collection.
// This is an alias for NewAuthorizer for cleaner API usage.
func Authorize(r *http.Request, collection *models.Collection, body map[string]any) *Authorizer {
	return rules.NewAuthorizer(r, collection, body)
}

← Back