Documentation ¶
Index ¶
- Constants
- Variables
- func Foot(ctx context.Context) (string, error)
- func GlobalsContextKey(global string) string
- func Head(ctx context.Context) markup.HeadProps
- func WithSettings(ctx context.Context, s *Settings) context.Context
- type Adapter
- type Block
- type Blocks
- type Form
- type FormBlockType
- type FormConfirmationType
- type FormEmail
- type FormField
- type FormOption
- type FormRedirect
- type FormSubmission
- type FormSubmissionDataEntry
- type Maintenance
- type MaintenanceRendererFunc
- type Media
- type MediaFields
- type MediaSize
- type MediaSizes
- type Navigation
- type NavigationItem
- type NavigationItems
- type NavigationWalkerFunc
- type Option
- func WithAPIKey(apiKey string) Option
- func WithBaseURL(url string) Option
- func WithCache(cache cache.Store) Option
- func WithGlobalMiddleware[T any](global string) Option
- func WithMaintenanceHandler(fn MaintenanceRendererFunc) Option
- func WithNavigation() Option
- func WithSilentLogs() Option
- func WithWebkit(kit *webkit.Kit) Option
- type RichText
- type Settings
- type SettingsAddress
- type SettingsCodeInjection
- type SettingsContact
- type SettingsMeta
- type SettingsSocial
Constants ¶
const ( // CollectionMedia defines the Payload media collection slug. CollectionMedia payloadcms.Collection = "media" // CollectionUsers defines the Payload users collection slug. CollectionUsers payloadcms.Collection = "users" // CollectionRedirects defines the Payload redirects collection slug. CollectionRedirects payloadcms.Collection = "redirects" // GlobalSettings defines the global settings slug. GlobalSettings payloadcms.Global = "settings" GlobalNavigation payloadcms.Global = "navigation" )
const ContextKeyPageMeta = "payload_page_meta"
const SettingsContextKey = "payload_settings"
SettingsContextKey defines the key for obtaining the settings from the context.
Variables ¶
var ErrSettingsNotFound = errors.New("settings not found in context")
ErrSettingsNotFound is returned when the settings are not found in the context.
Functions ¶
func GlobalsContextKey ¶
GlobalsContextKey returns the cache & context key for the global that resides in the context.
Types ¶
type Adapter ¶
type Adapter struct { *payloadcms.Client // contains filtered or unexported fields }
Adapter is a client that is used to interact with the Payload API and attach handlers and middleware to the HTTP Server.
Implicitly, it ensures that redirects, caching, settings and maintenance mode are handled natively.
func New ¶
New creates a new Payload adapter with the provided options.
The function applies functional options to configure the adapter and ensures that all required fields are set. It initializes the Payload CMS client and attaches handlers and middleware.
Example usage:
adapter, err := New( WithWebkit(webkit.New()), WithCache(cache.NewInMemory(time.Hour * 24)), WithBaseURL("https://api.payloadcms.com"), WithAPIKey("your-api-key"), ) if err != nil { log.Fatal(err) }
type Block ¶
type Block struct { // The ID of the block, this is generated by Payload and is used to // uniquely identify the block. ID string `json:"id,omitempty"` // The block type is saved as the slug of the block that has been selected. BlockType string `json:"blockType"` // The Admin panel provides each block with a blockName field which optionally // allows editors to label their blocks for better readability. BlockName *string `json:"blockName,omitempty"` // Arbitrary key-value pairs of the block's fields, these pairs are defined by // the block's schema and vary depending on the block type. Fields map[string]any `json:"-"` // RawJSON is the raw byte slice of the block, which can be used to decode // the block into a specific type. RawJSON json.RawMessage }
Block defines a common structure of a singular block layout from PayloadCMS.
See: https://payloadcms.com/docs/fields/blocks
func (*Block) Decode ¶
Decode decodes the block's raw JSON into the provided interface. This is optional, to be more performant, you make just access the fields directly.
func (*Block) SafeID ¶
SafeID generates a safe ID for the block instead of using the ID provided by Payload which contains numbers, inherently this is not a valid selector for HTML/CSS.
func (*Block) UnmarshalJSON ¶
UnmarshalJSON unmarshalls the JSON data into the Block type. This method is used to extract known fields and assign the remaining fields to the Fields map.
type Form ¶
type Form struct { // The ID of the block, this is generated by Payload and is used to // uniquely identify the block. ID float64 `json:"id"` // The title of the form, this is used to identify the form in the CMS. Title string `json:"title"` // The fields that appear in the form. Fields []FormField `json:"fields,omitempty"` // A label that is used to submit the form (e.g. "Submit", "Get In Touch") SubmitButtonLabel *string `json:"submitButtonLabel,omitempty"` // The type of confirmation message to display after submitting the form. ConfirmationType FormConfirmationType `json:"confirmationType,omitempty"` // Only appears when ConfirmationType is "message" // RichText, can be Slate or Lexical ConfirmationMessage any `json:"confirmationMessage,omitempty"` // Only appears when ConfirmationType is "redirect" Redirect *FormRedirect `json:"redirect,omitempty"` // Optional Emails []FormEmail `json:"emails,omitempty"` // Timestamps for when the item was created and last updated. // These are included by default from Payload. UpdatedAt string `json:"updatedAt"` CreatedAt string `json:"createdAt"` // Arbitrary key-value pairs of any other fields that appear within // the schema but are not defined in the struct. Extra map[string]any `json:"-"` // RawJSON is the raw byte slice of the block, which can be used to decode // the block into a specific type. RawJSON json.RawMessage `json:"-"` }
Form defines a singular form collection type in the Form Builder Plugin within Payload CMS
See: https://payloadcms.com/docs/plugins/form-builder
Blocks example within the frontend: https://github.com/payloadcms/payload/tree/main/examples/form-builder/next-pages/components/Blocks
TypeScript Bindings: https://github.com/payloadcms/payload/blob/main/packages/plugin-form-builder/src/types.ts
func (*Form) ButtonLabel ¶
ButtonLabel returns a label for the form's submit button.
func (*Form) UnmarshalJSON ¶
UnmarshalJSON unmarshalls the JSON data into the Settings type. This method is used to extract known fields and assign the remaining fields to the Extra map.
type FormBlockType ¶
type FormBlockType string
FormBlockType defines the type of field within a form. See: https://payloadcms.com/docs/plugins/form-builder#fields for more info.
const ( // FormBlockTypeCheckbox maps to a checkbox input on your front-end. // Used to collect a boolean value. FormBlockTypeCheckbox FormBlockType = "checkbox" // FormBlockTypeCountry maps to a select input on your front-end. // Used to collect a country. FormBlockTypeCountry FormBlockType = "country" // FormBlockTypeEmail maps to a text input with type email on your front-end. // Used to collect an email address. FormBlockTypeEmail FormBlockType = "email" // FormBlockTypeMessage maps to a RichText component on your front-end. // Used to display an arbitrary message to the user anywhere in the form. // // Not currently supported by WebKit. FormBlockTypeMessage FormBlockType = "message" // FormBlockTypeNumber maps to a number input on your front-end. // Used to collect a number. FormBlockTypeNumber FormBlockType = "number" // FormBlockTypeSelect maps to a select input on your front-end. // Used to display a list of options. FormBlockTypeSelect FormBlockType = "select" // FormBlockTypeState maps to a select input on your front-end. // Used to collect a US state. // // Not currently supported by WebKit (No US-specific features). FormBlockTypeState FormBlockType = "state" // FormBlockTypeText maps to a text input in your front-end. // Used to collect a simple string. FormBlockTypeText FormBlockType = "text" // FormBlockTypeTextarea maps to a textarea input on your front-end. // Used to collect a multi-line string. FormBlockTypeTextarea FormBlockType = "textarea" // FormBlockTypePayment is used to collect payments from forms. // Upon submission, the handlePayment callback is executed with the form and submission data. // You can use this to integrate with any third-party payment processing API. // // Not currently supported by WebKit FormBlockTypePayment FormBlockType = "payment" )
func (*FormBlockType) String ¶
func (f *FormBlockType) String() string
String implements the fmt.Stringer interface for FormBlockType.
func (*FormBlockType) UnmarshalJSON ¶
func (f *FormBlockType) UnmarshalJSON(data []byte) error
UnmarshalJSON unmarshals the JSON data into the FormBlockType type. Marshmallow doesn't seem to handle custom types.
type FormConfirmationType ¶
type FormConfirmationType string
FormConfirmationType defines the way in which a user is directed after submitting a form.
const ( // FormConfirmationTypeMessage displays a message to the user after submitting the form. FormConfirmationTypeMessage FormConfirmationType = "message" // FormConfirmationTypeRedirect redirects the user to a new page after submitting the form. FormConfirmationTypeRedirect FormConfirmationType = "redirect" )
type FormEmail ¶
type FormEmail struct { ID *string `json:"id,omitempty"` EmailTo *string `json:"emailTo,omitempty"` CC *string `json:"cc,omitempty"` BCC *string `json:"bcc,omitempty"` ReplyTo *string `json:"replyTo,omitempty"` EmailFrom *string `json:"emailFrom,omitempty"` Subject string `json:"subject"` Message []map[string]any `json:"message,omitempty"` }
FormEmail represents an email configuration for a form.
type FormField ¶
type FormField struct { // Tabs that appear in all block types. ID string `json:"id,omitempty"` BlockType FormBlockType `json:"blockType"` Name string `json:"name"` Label string `json:"label,omitempty"` Width *int `json:"width,omitempty"` Required *bool `json:"required,omitempty"` // One of the following fields must be present, depending on blockType DefaultValue *bool `json:"defaultValue,omitempty"` BlockName *string `json:"blockName,omitempty"` Message []map[string]any `json:"message,omitempty"` Options []FormOption `json:"options,omitempty"` // Value used for front-end only, Payload does not send this from their API. Value string `json:"value,omitempty"` }
FormField represents a field in the Payload form builder.
type FormOption ¶
type FormOption struct { ID *string `json:"id,omitempty"` Label string `json:"label"` Value string `json:"value"` }
FormOption defines a singular option within a select field.
type FormRedirect ¶
type FormRedirect struct {
URL string `json:"url"`
}
FormRedirect defines the type of confirmation message to display after
type FormSubmission ¶
type FormSubmission struct { ID int `json:"id"` Form Form `json:"form"` SubmissionData []FormSubmissionDataEntry `json:"submissionData,omitempty"` UpdatedAt time.Time `json:"updatedAt"` CreatedAt time.Time `json:"createdAt"` }
FormSubmission defines a singular submission to a form in the Form Builder Plugin within Payload CMS.
type FormSubmissionDataEntry ¶
type FormSubmissionDataEntry struct { ID *string `json:"id,omitempty"` Field string `json:"field"` Value string `json:"value"` }
FormSubmissionDataEntry defines a data entry within a form submission. These directly correspond to the fields within a form.
type Maintenance ¶
type Maintenance struct { Enabled bool `json:"enabled,omitempty"` Title string `json:"title,omitempty"` Content string `json:"content,omitempty"` }
Maintenance defines the fields for displaying an offline page to the front-end when it's been enabled within PayloadCMS.
func (*Maintenance) UnmarshalJSON ¶
func (m *Maintenance) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the custom unmarshalling logic for the Maintenance struct to make sure enabled is set to false if it's not present in the JSON data.
type MaintenanceRendererFunc ¶
type MaintenanceRendererFunc func(c *webkit.Context, m Maintenance) error
MaintenanceRendererFunc is the function that defines how the maintenance should be rendered on the site.
type Media ¶
type Media struct { // The ID of the block, this is generated by Payload and is used to // uniquely identify the block. ID float64 `json:"id"` // Initial media fields, these are also defined in each // media size. // // As per the Payload docs: filename, mimeType, and filesize fields // will be automatically added to the upload Collection. URL string `json:"url"` Filename string `json:"filename"` Filesize float64 `json:"filesize"` MimeType string `json:"mimeType"` Width *float64 `json:"width,omitempty"` Height *float64 `json:"height,omitempty"` // Key value map of media sizes. Sizes MediaSizes `json:"sizes,omitempty"` // Timestamps for when the item was created and last updated. // These are included by default from Payload. CreatedAt string `json:"createdAt,omitempty"` UpdatedAt string `json:"updatedAt,omitempty"` // Arbitrary key-value pairs of any other fields that appear within // the schema but are not defined in the struct. Extra MediaFields `json:"-"` // RawJSON is the raw byte slice of the block, which can be used to decode // the block into a specific type. RawJSON json.RawMessage `json:"-"` }
Media defines the fields for media when they are uploaded to PayloadCMS.
See: https://payloadcms.com/docs/upload/overview
func (*Media) Alt ¶
Alt returns the alt text for the media item if it's defined as a field, otherwise it returns the first defaultValue if provided, or an empty string if no defaultValue is given.
func (*Media) Caption ¶
Caption returns the caption text for the media item if it's defined as a field, otherwise it returns the first defaultValue if provided, or an empty string if no defaultValue is given.
func (*Media) ImageMarkup ¶
func (m *Media) ImageMarkup() markup.ImageProps
ImageMarkup implements the markup.ImageProvider interface and transforms the Media item into a markup.ImageProps type ready for rendering an <img> to the DOM.
func (*Media) PictureMarkup ¶
func (m *Media) PictureMarkup() markup.PictureProps
PictureMarkup implements the markup.PictureProvider interface and transforms the Media item into a markup.PictureProps type ready for rendering a <picture> the DOM.
func (*Media) UnmarshalJSON ¶
UnmarshalJSON unmarshals the JSON data into the Media type. This method is used to extract known fields and assign the remaining fields to the fields map.
type MediaFields ¶
MediaFields defines a dictionary of arbitrary fields that are not defined in the PayloadCMS schema.
type MediaSize ¶
type MediaSize struct { Size string `json:"-"` // Name of the media size e.g. (thumbnail, small, medium, large) URL string `json:"url,omitempty"` Filename *string `json:"filename,omitempty"` Filesize *float64 `json:"filesize,omitempty"` MimeType *string `json:"mimeType,omitempty"` Width *float64 `json:"width,omitempty"` Height *float64 `json:"height,omitempty"` }
MediaSize defines the fields for the different sizes of media when they are uploaded to PayloadCMS.
type MediaSizes ¶
MediaSizes defines a dictionary of media sizes by size name (e.g. "small", "medium", "large").
func (MediaSizes) SortByWidth ¶
func (ms MediaSizes) SortByWidth() []MediaSize
SortByWidth sorts the media sizes by width from lowest to highest. If a width is nil, it will consistently appear at the end.
type Navigation ¶
type Navigation struct { // within Payload settings. Header NavigationItems `json:"header,omitempty"` Footer NavigationItems `json:"footer,omitempty"` // the schema but are not defined in the struct. Tabs map[string]any `json:"-"` }
Navigation defines a common structure of a navigation layout
func (*Navigation) UnmarshalJSON ¶
func (n *Navigation) UnmarshalJSON(data []byte) error
UnmarshalJSON unmarshalls the JSON data into the Navigation type. This method is used to extract known fields and assign the remaining fields to the Tabs map.
type NavigationItem ¶
type NavigationItem struct { // uniquely identify the li k. ID string `json:"id,omitempty"` Title string `json:"title"` URL string `json:"url"` Image Media `json:"image,omitempty"` // defined within the Payload settings. Children NavigationItems `json:"children"` // the schema but are not defined in the struct. Fields map[string]any `json:"-"` }
NavigationItem defines a common structure of a singular navigation item from PayloadCMS.
func (*NavigationItem) HasChildren ¶
func (n *NavigationItem) HasChildren() bool
HasChildren returns true if the NavigationItem has children, false otherwise.
func (*NavigationItem) IsActive ¶
func (n *NavigationItem) IsActive(path string) bool
IsActive checks if the provided path matches the URL of the NavigationItem or any of its children recursively.
This function is useful for highlighting the active navigation item in the UI.
func (*NavigationItem) IsRelativeURL ¶
func (n *NavigationItem) IsRelativeURL() bool
IsRelativeURL checks if the URL is a relative URL. It returns true if the URL is relative, false otherwise.
func (*NavigationItem) UnmarshalJSON ¶
func (n *NavigationItem) UnmarshalJSON(data []byte) error
UnmarshalJSON unmarshalls the JSON data into the NavigationItem type. This method is used to extract known fields and assign the remaining fields to the Fields map.
type NavigationItems ¶
type NavigationItems []NavigationItem
NavigationItems is a collection of NavigationItem types.
func (NavigationItems) Len ¶
func (n NavigationItems) Len() int
Len returns the length of the NavigationItems collection.
func (NavigationItems) MaxDepth ¶
func (n NavigationItems) MaxDepth() int
MaxDepth returns the maximum depth of the NavigationItems collection. Index starts at 1, so if there is one nav menu with no children, the depth is 1. If there is one nav menu with one child, the depth is 2.
func (NavigationItems) Walk ¶
func (n NavigationItems) Walk(walker NavigationWalkerFunc)
Walk recursively visits each NavigationItem and its children.
type NavigationWalkerFunc ¶
type NavigationWalkerFunc func(index int, item *NavigationItem)
NavigationWalkerFunc defines the signature for the walker function.
type Option ¶
type Option func(a *Adapter)
Option is a functional option type that allows us to configure the Client.
func WithAPIKey ¶
WithAPIKey is a functional option to set the API key for the Payload API. To get an API key, visit: https://payloadcms.com/docs/rest-api/overview#authentication
Usually, you can obtain one by enabling auth on the users type, and visiting the users collection in the Payload dashboard.
func WithBaseURL ¶
WithBaseURL is a functional option to set the base URL of the Payload API. Example: https://api.payloadcms.com
func WithGlobalMiddleware ¶
WithGlobalMiddleware is a functional option to set the global middleware for the adapter. The global middleware is applied to all requests and can be used to inject common data into the context.
Global data can be accessed by using GlobalsContextKey(global)
Example: payload.WithGlobalMiddleware[types.Navigation]("navigation")
func WithMaintenanceHandler ¶
func WithMaintenanceHandler(fn MaintenanceRendererFunc) Option
WithMaintenanceHandler is a functional option to set the maintenance handler for the adapter. The maintenance handler is called when the site is in maintenance mode.
func WithNavigation ¶
func WithNavigation() Option
WithNavigation is a functional option to set the navigation global middleware for the adapter. The navigation middleware is used to inject the navigation data into the context.
func WithSilentLogs ¶
func WithSilentLogs() Option
WithSilentLogs is a functional option to disable logs from all handlers and middleware.
func WithWebkit ¶
WithWebkit is a functional option to set the Webkit instance.
type RichText ¶
type RichText any
RichText is a string type that represents a rich text content from the Payload lexical editor.
type Settings ¶
type Settings struct { ID float64 `json:"id"` SiteName *string `json:"siteName,omitempty"` TagLine *string `json:"tagLine,omitempty"` Locale string `json:"locale,omitempty"` // In en_GB format Logo *Media `json:"logo,omitempty"` Meta SettingsMeta `json:"meta"` Robots *string `json:"robots,omitempty"` CodeInjection *SettingsCodeInjection `json:"codeInjection,omitempty"` Maintenance *Maintenance `json:"maintenance,omitempty"` Contact *SettingsContact `json:"contact,omitempty"` Social *SettingsSocial `json:"social,omitempty"` Address *SettingsAddress `json:"address,omitempty"` UpdatedAt *time.Time `json:"updatedAt,omitempty"` CreatedAt *time.Time `json:"createdAt,omitempty"` Extra map[string]any `json:"-"` // Extra fields that are not defined in the struct. }
Settings defines the common global collection type within Payload that allows users to change site settings.
func GetSettings ¶
GetSettings is a helper function to get the settings from the context. If the settings are not found, it returns an error.
func MustGetSettings ¶
MustGetSettings is a helper function to get the settings from the context. If the settings are not found, it logs an error and returns nil.
func (*Settings) OpenGraph ¶
OpenGraph transforms the settings into an Open Graph object for use in the head of the frontend.
func (*Settings) SchemaOrganisation ¶
func (s *Settings) SchemaOrganisation(url string) *schemaorg.Organisation
SchemaOrganisation transforms the settings into a Schema.org Organisation structure for use in the head of the frontend.
func (*Settings) TwitterCard ¶
func (s *Settings) TwitterCard() *markup.TwitterCard
TwitterCard transforms the settings into a Twitter Card for use in the head of the frontend.
func (*Settings) UnmarshalJSON ¶
UnmarshalJSON unmarshalls the JSON data into the Settings type. This method is used to extract known fields and assign the remaining fields to the Extra map.
type SettingsAddress ¶
type SettingsAddress struct { Line1 *string `json:"line1,omitempty"` Line2 *string `json:"line2,omitempty"` City *string `json:"city,omitempty"` Country *string `json:"country,omitempty"` County *string `json:"county,omitempty"` Postcode *string `json:"postcode,omitempty"` }
SettingsAddress defines the fields for a company address.
func (SettingsAddress) Format ¶
func (a SettingsAddress) Format() string
Format returns the address as a comma-delimited string, excluding nil fields.
type SettingsCodeInjection ¶
type SettingsCodeInjection struct { Head *string `json:"head,omitempty"` }
SettingsCodeInjection defines the fields for injecting code into the head or foot of the frontend.
type SettingsContact ¶
type SettingsContact struct { Email *string `json:"email,omitempty"` Telephone *string `json:"telephone,omitempty"` }
SettingsContact defines the fields for contact details for the company.
type SettingsMeta ¶
type SettingsMeta struct { Title *string `json:"title,omitempty"` Description *string `json:"description,omitempty"` Image *Media `json:"image,omitempty"` Private *bool `json:"private,omitempty"` CanonicalURL *string `json:"canonicalURL,omitempty"` StructuredData any `json:"structuredData,omitempty"` }
SettingsMeta defines the data generated by the Meta plugin from Payload along with additional fields such as Private & Canonical.
The SEO plugin appears in the majority of collections and in both the Global Settings and Page level fields.
type SettingsSocial ¶
type SettingsSocial struct { Facebook *string `json:"facebook,omitempty"` Instagram *string `json:"instagram,omitempty"` LinkedIn *string `json:"linkedIn,omitempty"` Tiktok *string `json:"tiktok,omitempty"` X *string `json:"x,omitempty"` Youtube *string `json:"youtube,omitempty"` }
SettingsSocial defines the fields for social media links.
func (SettingsSocial) StringArray ¶
func (s SettingsSocial) StringArray() []string
StringArray returns the social media links as an array of strings.