contentful

package module
v0.0.0-...-fca960e Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2023 License: MIT Imports: 14 Imported by: 1

README

codecov Godoc Build Status

contentful-go

GoLang SDK for Contentful's Content Delivery, Preview and Management API's.

About

Contentful provides a content infrastructure for digital teams to power content in websites, apps, and devices. Unlike a CMS, Contentful was built to integrate with the modern software stack. It offers a central hub for structured content, powerful management and delivery APIs, and a customizable web app that enables developers and content creators to ship digital products faster.

Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.

Install

go get github.com/labd/contentful-go

Getting started

Import the SDK into your Go project or library

import (
	contentful "github.com/labd/contentful-go"
)

Create an API client in order to interact with the Contentful's API endpoints.

token := "your-cma-token" // Observe your CMA token from Contentful's web page
cma := contentful.NewCMA(token)
Organization

If your Contentful account is part of an organization, you can setup your API client as such. When you set your organization id for the SDK client, every API request will have the X-Contentful-Organization: <your-organization-id> header automatically.

cma.SetOrganization("your-organization-id")
Debug mode

When debug mode is activated, the SDK client starts to work in verbose mode and tries to print as much information as possible. In debug mode, all outgoing HTTP requests are printed nicely in the form of curl commands so that you can easily drop into your command line to debug specific requests.

cma.Debug = true
Dependencies

contentful-go stores its dependencies under the vendor folder and uses dep to manage dependency resolutions. Dependencies in the vendor folder will be loaded automatically by Go 1.6+. To install the dependencies, run dep ensure, for more options and documentation please visit dep.

Using the SDK

Working with resource services

Currently, the SDK exposes the following services:

  • Access Tokens
  • API Keys
  • App Definitions
  • App Installations
  • Assets
  • Content Types
  • Editor Interfaces
  • Entries
  • Environments
  • Extensions
  • Locales
  • Memberships
  • Organizations
  • Resources/Uploads
  • Roles
  • Scheduled Actions
  • Snapshots
  • Spaces
  • Usage
  • Users
  • Webhooks
  • Webhook Calls and Health

Every service has multiple interface, for example:

List() *Collection
Get(spaceID, resourceID string) <Resource>, error
Upsert(spaceID string, resourceID *Resource) error
Delete(spaceID string, resourceID *Resource) error

To read the interfaces of all services, visit the Contentful GoDoc.

Examples

In the example below, the Get interface of the Spaces service is called. This interface returns an object of the type Space. This object could be easily read later by calling the properties of the interface, for example: Space.Name

space, err := cma.Spaces.Get("space-id")
if err != nil {
  log.Fatal(err)
}

In the following example, the List interface of the Spaces service is called. This interface returns an array of Space objects. Working with these collections is explained below.

collection := cma.ContentTypes.List(space.Sys.ID)
collection, err = collection.Next()
if err != nil {
  log.Fatal(err)
}

for _, contentType := range collection.ToContentType() {
  fmt.Println(contentType.Name, contentType.Description)
}

Working with collections

All the endpoints which return an array of objects are wrapped with the Collection struct. The main features of the Collection struct are pagination and type assertion.

Type assertion

The Collection struct exposes the necessary converters (type assertions) such as ToSpace(). The following example gets all spaces for the given account:

Example
collection := cma.Spaces.List() // returns a collection
collection, err := collection.Next() // makes the actual api call
if err != nil {
  log.Fatal(err)
}

spaces := collection.ToSpace() // make the type assertion
for _, space := range spaces {
  fmt.Println(space.Name)
  fmt.Println(space.Sys.ID)
}

// In order to access collection metadata
fmt.Println(col.Total)
fmt.Println(col.Skip)
fmt.Println(col.Limit)

Testing

$> go test

To enable higher verbose mode

$> go test -v

Documentation/References

Contentful

Content Delivery API Content Management API Content Preview API

GoLang

Effective Go

Support

This is a project created for demo purposes and not officially supported, so if you find issues or have questions you can let us know via the issue page but don't expect a quick and prompt response.

Contributing

[WIP]

License

MIT

Documentation

Index

Examples

Constants

View Source
const (
	// FieldTypeText content type field type for text data
	FieldTypeText = "Text"

	// FieldTypeSymbol content type field type for text data
	FieldTypeSymbol = "Symbol"

	// FieldTypeArray content type field type for array data
	FieldTypeArray = "Array"

	// FieldTypeLink content type field type for link data
	FieldTypeLink = "Link"

	// FieldTypeInteger content type field type for integer data
	FieldTypeInteger = "Integer"

	// FieldTypeLocation content type field type for location data
	FieldTypeLocation = "Location"

	// FieldTypeBoolean content type field type for boolean data
	FieldTypeBoolean = "Boolean"

	// FieldTypeDate content type field type for date data
	FieldTypeDate = "Date"

	// FieldTypeObject content type field type for object data
	FieldTypeObject = "Object"

	// FieldTypeRichText content type field type for rich text data
	FieldTypeRichText = "RichText"
)

noinspection GoUnusedConst

View Source
const (
	// MimeTypeAttachment mime type validation for content type field
	MimeTypeAttachment = "attachment"

	// MimeTypePlainText mime type validation for content type field
	MimeTypePlainText = "plaintext"

	// MimeTypeImage mime type validation for content type field
	MimeTypeImage = "image"

	// MimeTypeAudio mime type validation for content type field
	MimeTypeAudio = "audio"

	// MimeTypeVideo mime type validation for content type field
	MimeTypeVideo = "video"

	// MimeTypeRichText mime type validation for content type field
	MimeTypeRichText = "richtext"

	// MimeTypePresentation mime type validation for content type field
	MimeTypePresentation = "presentation"

	// MimeTypeSpreadSheet mime type validation for content type field
	MimeTypeSpreadSheet = "spreadsheet"

	// MimeTypePDF mime type validation for content type field
	MimeTypePDF = "pdfdocument"

	// MimeTypeArchive mime type validation for content type field
	MimeTypeArchive = "archive"

	// MimeTypeCode mime type validation for content type field
	MimeTypeCode = "code"

	// MimeTypeMarkup mime type validation for content type field
	MimeTypeMarkup = "markup"
)
View Source
const (
	// FieldValidationRegexPatternEmail email validation
	FieldValidationRegexPatternEmail = `^\w[\w.-]*@([\w-]+\.)+[\w-]+$`

	// FieldValidationRegexPatternURL url validation
	FieldValidationRegexPatternURL = `^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$`

	// FieldValidationRegexPatternUSDate us date validation
	FieldValidationRegexPatternUSDate = `^(0?[1-9]|[12][0-9]|3[01])[- \/.](0?[1-9]|1[012])[- \/.](19|20)?\d\d$`

	// FieldValidationRegexPatternEuorpeanDate euorpean date validation
	FieldValidationRegexPatternEuorpeanDate = `^(0?[1-9]|[12][0-9]|3[01])[- \/.](0?[1-9]|1[012])[- \/.](19|20)?\d\d$`

	// FieldValidationRegexPattern12HourTime 12-hour time validation
	FieldValidationRegexPattern12HourTime = `^(0?[1-9]|1[012]):[0-5][0-9](:[0-5][0-9])?\s*[aApP][mM]$`

	// FieldValidationRegexPattern24HourTime 24-hour time validation
	FieldValidationRegexPattern24HourTime = `^(0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$`

	// FieldValidationRegexPatternUSPhoneNumber us phone number validation
	FieldValidationRegexPatternUSPhoneNumber = `^\d[ -.]?\(?\d\d\d\)?[ -.]?\d\d\d[ -.]?\d\d\d\d$`

	// FieldValidationRegexPatternUSZipCode us zip code validation
	FieldValidationRegexPatternUSZipCode = `^\d{5}$|^\d{5}-\d{4}$}`
)

noinspection GoUnusedConst

View Source
const (
	// FieldValidationNodeTypeHeading1 Heading 1 node validation token
	FieldValidationNodeTypeHeading1 = "heading-1"

	// FieldValidationNodeTypeHeading2 Heading 2 node validation token
	FieldValidationNodeTypeHeading2 = "heading-2"

	// FieldValidationNodeTypeHeading3 Heading 3 node validation token
	FieldValidationNodeTypeHeading3 = "heading-3"

	// FieldValidationNodeTypeHeading4 Heading 4 node validation token
	FieldValidationNodeTypeHeading4 = "heading-4"

	// FieldValidationNodeTypeHeading5 Heading 5 node validation token
	FieldValidationNodeTypeHeading5 = "heading-5"

	// FieldValidationNodeTypeHeading6 Heading 6 node validation token
	FieldValidationNodeTypeHeading6 = "heading-6"

	// FieldValidationNodeTypeOrderedList Ordered list node validation token
	FieldValidationNodeTypeOrderedList = "ordered-list"

	// FieldValidationNodeTypeUnorderedList Unordered list node validation token
	FieldValidationNodeTypeUnorderedList = "unordered-list"

	// FieldValidationNodeTypeHorizontalRule Horizontal rule node validation token
	FieldValidationNodeTypeHorizontalRule = "hr"

	// FieldValidationNodeTypeBlockquote Blockquote node validation token
	FieldValidationNodeTypeBlockquote = "blockquote"

	// FieldValidationNodeTypeEmbeddedAssetBlock Asset block node validation token
	FieldValidationNodeTypeEmbeddedAssetBlock = "embedded-asset-block"

	// FieldValidationNodeTypeEmbeddedEntryLine Inline entry node validation token
	FieldValidationNodeTypeEmbeddedEntryLine = "embedded-entry-inline"

	// FieldValidationNodeTypeEmbeddedEntryBlock Block entry node validation token
	FieldValidationNodeTypeEmbeddedEntryBlock = "embedded-entry-block"

	// FieldValidationNodeTypeHyperlink Hyperlink node validation token
	FieldValidationNodeTypeHyperlink = "hyperlink"

	// FieldValidationNodeTypeEntryHyperlink Entry hyperlink node validation token
	FieldValidationNodeTypeEntryHyperlink = "entry-hyperlink"

	// FieldValidationNodeTypeAssetHyperlink Asset hyperlink node validation token
	FieldValidationNodeTypeAssetHyperlink = "asset-hyperlink"
)
View Source
const (
	// FieldValidationMarkItalic Italic mark validation token
	FieldValidationMarkItalic = "italic"

	// FieldValidationMarkUnderline Unerline mark validation token
	FieldValidationMarkUnderline = "underline"

	// FieldValidationMarkBold Bold mark validation token
	FieldValidationMarkBold = "bold"

	// FieldValidationMarkCode Code validation token
	FieldValidationMarkCode = "code"
)

Variables

View Source
var Version = "0.7.0"

Version for SDK Version

Functions

This section is empty.

Types

type APIError

type APIError struct {
	// contains filtered or unexported fields
}

APIError model

func (APIError) ErrorResponse

func (a APIError) ErrorResponse() (*ErrorResponse, bool)

type APIKey

type APIKey struct {
	Sys           *Sys            `json:"sys,omitempty"`
	Name          string          `json:"name,omitempty"`
	Description   string          `json:"description,omitempty"`
	AccessToken   string          `json:"accessToken,omitempty"`
	Policies      []*APIKeyPolicy `json:"policies,omitempty"`
	PreviewAPIKey PreviewAPIKey   `json:"preview_api_key,omitempty"`
	Environments  []Environments  `json:"environments,omitempty"`
}

APIKey model

func (*APIKey) GetVersion

func (apiKey *APIKey) GetVersion() int

GetVersion returns entity version

func (*APIKey) MarshalJSON

func (apiKey *APIKey) MarshalJSON() ([]byte, error)

MarshalJSON for custom json marshaling

type APIKeyPolicy

type APIKeyPolicy struct {
	Effect  string `json:"effect,omitempty"`
	Actions string `json:"actions,omitempty"`
}

APIKeyPolicy model

type APIKeyService

type APIKeyService service

APIKeyService service

func (*APIKeyService) Delete

func (service *APIKeyService) Delete(ctx context.Context, spaceID string, apiKey *APIKey) error

Delete deletes a sinlge api key entity

func (*APIKeyService) Get

func (service *APIKeyService) Get(ctx context.Context, spaceID, apiKeyID string) (*APIKey, error)

Get returns a single api key entity

func (*APIKeyService) List

func (service *APIKeyService) List(ctx context.Context, spaceID string, query *Query) (*Collection[APIKey], error)

List returns all api keys collection

func (*APIKeyService) Upsert

func (service *APIKeyService) Upsert(ctx context.Context, spaceID string, apiKey *APIKey) error

Upsert updates or creates a new api key entity

type AccessDeniedError

type AccessDeniedError struct{}

AccessDeniedError error model for access denied responses

type AccessToken

type AccessToken struct {
	Sys       *Sys     `json:"sys,omitempty"`
	Name      string   `json:"name,omitempty"`
	RevokedAt string   `json:"revokedAt,omitempty"`
	Scopes    []string `json:"scopes,omitempty"`
}

AccessToken model

func (*AccessToken) GetVersion

func (accessToken *AccessToken) GetVersion() int

GetVersion returns entity version

type AccessTokenInvalidError

type AccessTokenInvalidError struct {
	APIError
}

AccessTokenInvalidError for 401 errors

func (AccessTokenInvalidError) Error

func (e AccessTokenInvalidError) Error() string

type AccessTokensService

type AccessTokensService service

AccessTokensService service

func (*AccessTokensService) Create

func (service *AccessTokensService) Create(ctx context.Context, accessToken *AccessToken) error

Create creates a new access token

func (*AccessTokensService) Get

func (service *AccessTokensService) Get(ctx context.Context, accessTokenID string) (*AccessToken, error)

Get returns a single access token

func (*AccessTokensService) List

func (service *AccessTokensService) List(ctx context.Context, query *Query) (*Collection[AccessToken], error)

List returns an access tokens collection

func (*AccessTokensService) Revoke

func (service *AccessTokensService) Revoke(ctx context.Context, accessToken *AccessToken) error

Revoke revokes a personal access token

type AliasDetail

type AliasDetail struct {
	Sys *Sys `json:"sys"`
}

AliasDetail model

type AppDefinition

type AppDefinition struct {
	Sys       *Sys        `json:"sys"`
	Name      string      `json:"name"`
	SRC       string      `json:"src"`
	Locations []Locations `json:"locations"`
}

AppDefinition model

func (*AppDefinition) GetVersion

func (appDefinition *AppDefinition) GetVersion() int

GetVersion returns entity version

type AppDefinitionsService

type AppDefinitionsService service

AppDefinitionsService service

func (*AppDefinitionsService) Delete

func (service *AppDefinitionsService) Delete(ctx context.Context, organizationID, appDefinitionID string) error

Delete the app definition

func (*AppDefinitionsService) Get

func (service *AppDefinitionsService) Get(ctx context.Context, organizationID, appDefinitionID string) (*AppDefinition, error)

Get returns a single app definition

func (*AppDefinitionsService) List

func (service *AppDefinitionsService) List(ctx context.Context, organizationID string, query *Query) (*Collection[AppDefinition], error)

List returns an app definitions collection

func (*AppDefinitionsService) Upsert

func (service *AppDefinitionsService) Upsert(ctx context.Context, organizationID string, definition *AppDefinition) error

Upsert updates or creates a new app definition

type AppInstallation

type AppInstallation struct {
	Sys        *Sys              `json:"sys"`
	Parameters map[string]string `json:"parameters"`
}

AppInstallation model

func (*AppInstallation) GetVersion

func (appInstallation *AppInstallation) GetVersion() int

GetVersion returns entity version

type AppInstallationsService

type AppInstallationsService service

AppInstallationsService service

func (*AppInstallationsService) Delete

func (service *AppInstallationsService) Delete(ctx context.Context, spaceID, appInstallationID string) error

Delete the app installation

func (*AppInstallationsService) Get

func (service *AppInstallationsService) Get(ctx context.Context, spaceID, appInstallationID string) (*AppInstallation, error)

Get returns a single app installation

func (*AppInstallationsService) List

func (service *AppInstallationsService) List(ctx context.Context, spaceID string, query *Query) (*Collection[AppInstallation], error)

List returns an app installations collection

func (*AppInstallationsService) Upsert

func (service *AppInstallationsService) Upsert(ctx context.Context, spaceID, appInstallationID string, installation *AppInstallation) error

Upsert updates or creates a new app installation

type Asset

type Asset struct {
	Locale string
	Sys    *Sys         `json:"sys,omitempty"`
	Fields *AssetFields `json:"fields,omitempty"`
}

Asset represents a Contentful asset

func (*Asset) GetVersion

func (asset *Asset) GetVersion() int

GetVersion returns entity version

type AssetFields

type AssetFields struct {
	Title       LocaleItem[string] `json:"title,omitempty"`
	Description LocaleItem[string] `json:"description,omitempty"`
	File        LocaleItem[File]   `json:"file,omitempty"`
}

AssetFields model

type AssetsService

type AssetsService service

AssetsService service

func (*AssetsService) Archive

func (service *AssetsService) Archive(ctx context.Context, spaceID string, asset *Asset) error

Archive archives the asset

func (*AssetsService) Delete

func (service *AssetsService) Delete(ctx context.Context, spaceID string, asset *Asset) error

Delete sends delete request

func (*AssetsService) Get

func (service *AssetsService) Get(ctx context.Context, spaceID, assetID string) (*Asset, error)

Get returns a single asset entity

func (*AssetsService) List

func (service *AssetsService) List(ctx context.Context, spaceID string, query *Query) (*Collection[Asset], error)

List returns asset collection

func (*AssetsService) ListPublished

func (service *AssetsService) ListPublished(ctx context.Context, spaceID string, query *Query) (*Collection[Asset], error)

ListPublished return a content type collection, with only activated content types

func (*AssetsService) Process

func (service *AssetsService) Process(ctx context.Context, spaceID string, asset *Asset) error

Process the asset

func (*AssetsService) Publish

func (service *AssetsService) Publish(ctx context.Context, spaceID string, asset *Asset) error

Publish published the asset

func (*AssetsService) Unarchive

func (service *AssetsService) Unarchive(ctx context.Context, spaceID string, asset *Asset) error

Unarchive unarchives the asset

func (*AssetsService) Unpublish

func (service *AssetsService) Unpublish(ctx context.Context, spaceID string, asset *Asset) error

Unpublish the asset

func (*AssetsService) Upsert

func (service *AssetsService) Upsert(ctx context.Context, spaceID string, asset *Asset) error

Upsert updates or creates a new asset entity

type AssignedTo

type AssignedTo struct {
	Sys Sys `json:"sys"`
}

AssignedTo model

type BadRequestError

type BadRequestError struct{}

BadRequestError error model for bad request responses

type Client

type Client struct {
	Debug       bool
	QueryParams map[string]string
	Headers     map[string]string
	BaseURL     string
	Environment string

	Spaces             *SpacesService
	Users              *UsersService
	Environments       *EnvironmentsService
	EnvironmentAliases *EnvironmentAliasesService
	Organizations      *OrganizationsService
	Roles              *RolesService
	Memberships        *MembershipsService
	Snapshots          *SnapshotsService
	APIKeys            *APIKeyService
	AccessTokens       *AccessTokensService
	Assets             *AssetsService
	ContentTypes       *ContentTypesService
	Entries            *EntriesService
	EntryTasks         *EntryTasksService
	ScheduledActions   *ScheduledActionsService
	Locales            *LocalesService
	Webhooks           *WebhooksService
	WebhookCalls       *WebhookCallsService
	EditorInterfaces   *EditorInterfacesService
	Extensions         *ExtensionsService
	AppDefinitions     *AppDefinitionsService
	AppInstallations   *AppInstallationsService
	Usages             *UsagesService
	Resources          *ResourcesService
	// contains filtered or unexported fields
}

Client model

func NewCDA

func NewCDA(token string) *Client

NewCDA returns a CDA client

func NewCMA

func NewCMA(token string) *Client

NewCMA returns a CMA client

func NewCPA

func NewCPA(token string) *Client

NewCPA returns a CPA client

func NewResourceClient

func NewResourceClient(token string) *Client

NewResourceClient returns a client for the resource/uploads endpoints

func (*Client) SetEnvironment

func (c *Client) SetEnvironment(environment string) *Client

SetEnvironment sets the given environment. https://www.contentful.com/developers/docs/references/content-management-api/#/reference/environments

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(client *http.Client)

SetHTTPClient sets the underlying http.Client used to make requests.

func (*Client) SetOrganization

func (c *Client) SetOrganization(organizationID string) *Client

SetOrganization sets the given organization id

type Collection

type Collection[T any] struct {
	Sys      *Sys        `json:"sys"`
	Total    int         `json:"total"`
	Skip     int         `json:"skip"`
	Limit    int         `json:"limit"`
	Items    []T         `json:"items"`
	Includes interface{} `json:"includes"`
	// contains filtered or unexported fields
}

Collection model

func (*Collection[T]) Next

func (col *Collection[T]) Next(ctx context.Context) (*Collection[T], error)

Next makes the col.req

type CollectionOptions

type CollectionOptions struct {
	Limit uint16
}

CollectionOptions holds init options

type Constraint

type Constraint struct {
	And   any `json:"and"`
	Equal any `json:"equal"`
	Or    any `json:"or"`
	Not   any `rson:"not"`
}

Constraint model

type ContentType

type ContentType struct {
	Sys          *Sys     `json:"sys"`
	Name         string   `json:"name,omitempty"`
	Description  string   `json:"description,omitempty"`
	Fields       []*Field `json:"fields,omitempty"`
	DisplayField string   `json:"displayField,omitempty"`
}

ContentType model

func (*ContentType) GetVersion

func (ct *ContentType) GetVersion() int

GetVersion returns entity version

type ContentTypeFields

type ContentTypeFields struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Required  bool   `json:"required"`
	Localized bool   `json:"localized"`
	Type      string `json:"type"`
}

ContentTypeFields model

type ContentTypeSnapshot

type ContentTypeSnapshot struct {
	Sys                       *Sys                      `json:"sys"`
	ContentTypeSnapshotDetail ContentTypeSnapshotDetail `json:"snapshot"`
}

ContentTypeSnapshot model

type ContentTypeSnapshotDetail

type ContentTypeSnapshotDetail struct {
	Name   string              `json:"name"`
	Fields []ContentTypeFields `json:"fields"`
	Sys    *Sys                `json:"sys"`
}

ContentTypeSnapshotDetail model

type ContentTypesService

type ContentTypesService service

ContentTypesService service

func (*ContentTypesService) Activate

func (service *ContentTypesService) Activate(ctx context.Context, env *Environment, ct *ContentType) error

Activate activate a content type for a specified environment

Example
cma := NewCMA("cma-token")

contentType, err := cma.ContentTypes.Get(context.Background(), env, "content-type-id")
if err != nil {
	log.Fatal(err)
}

err = cma.ContentTypes.Activate(context.Background(), env, contentType)
if err != nil {
	log.Fatal(err)
}
Output:

func (*ContentTypesService) Deactivate

func (service *ContentTypesService) Deactivate(ctx context.Context, env *Environment, ct *ContentType) error

Deactivate deactivate a contenttype for a specified environment

Example
cma := NewCMA("cma-token")

contentType, err := cma.ContentTypes.Get(context.Background(), env, "content-type-id")
if err != nil {
	log.Fatal(err)
}

err = cma.ContentTypes.Deactivate(context.Background(), env, contentType)
if err != nil {
	log.Fatal(err)
}
Output:

func (*ContentTypesService) Delete

func (service *ContentTypesService) Delete(ctx context.Context, env *Environment, ct *ContentType) error

Delete a content type from an environment

Example
cma := NewCMA("cma-token")

contentType, err := cma.ContentTypes.Get(context.Background(), env, "content-type-id")
if err != nil {
	log.Fatal(err)
}

err = cma.ContentTypes.Delete(context.Background(), env, contentType)
if err != nil {
	log.Fatal(err)
}
Output:

Example (AllDrafts)
cma := NewCMA("cma-token")

collection, err := cma.ContentTypes.List(context.Background(), env, nil)
if err != nil {
	log.Fatal(err)
}

contentTypes := collection.Items

for _, contentType := range contentTypes {
	if contentType.Sys.PublishedAt == "" {
		err := cma.ContentTypes.Delete(context.Background(), env, &contentType)
		if err != nil {
			log.Fatal(err)
		}
	}
}
Output:

func (*ContentTypesService) Get

func (service *ContentTypesService) Get(ctx context.Context, env *Environment, contentTypeID string) (*ContentType, error)

Get a content type by `contentTypeID` from an environment

Example
cma := NewCMA("cma-token")

contentType, err := cma.ContentTypes.Get(context.Background(), env, "content-type-id")
if err != nil {
	log.Fatal(err)
}

fmt.Println(contentType.Name)
Output:

func (*ContentTypesService) List

func (service *ContentTypesService) List(ctx context.Context, env *Environment, query *Query) (*Collection[ContentType], error)

List return a content type collection

Example
cma := NewCMA("cma-token")

collection, err := cma.ContentTypes.List(context.Background(), env, nil)
if err != nil {
	log.Fatal(err)
}

contentTypes := collection.Items

for _, contentType := range contentTypes {
	fmt.Println(contentType.Sys.ID, contentType.Sys.PublishedAt)
}
Output:

func (*ContentTypesService) ListActivated

func (service *ContentTypesService) ListActivated(ctx context.Context, env *Environment, query *Query) (*Collection[ContentType], error)

ListActivated return a content type collection, with only activated content types

func (*ContentTypesService) Upsert

func (service *ContentTypesService) Upsert(ctx context.Context, env *Environment, ct *ContentType) error

Upsert a content type to the specified environment

Example (Create)
cma := NewCMA("cma-token")

contentType := &ContentType{
	Name:         "test content type",
	DisplayField: "field1_id",
	Description:  "content type description",
	Fields: []*Field{
		{
			ID:       "field1_id",
			Name:     "field1",
			Type:     "Symbol",
			Required: false,
			Disabled: false,
		},
		{
			ID:       "field2_id",
			Name:     "field2",
			Type:     "Symbol",
			Required: false,
			Disabled: true,
		},
	},
}

err := cma.ContentTypes.Upsert(context.Background(), env, contentType)
if err != nil {
	log.Fatal(err)
}
Output:

Example (Update)
cma := NewCMA("cma-token")

contentType, err := cma.ContentTypes.Get(context.Background(), env, "content-type-id")
if err != nil {
	log.Fatal(err)
}

contentType.Name = "modified content type name"

err = cma.ContentTypes.Upsert(context.Background(), env, contentType)
if err != nil {
	log.Fatal(err)
}
Output:

type Controls

type Controls struct {
	FieldID         string            `json:"fieldId"`
	WidgetNameSpace string            `json:"widgetNamespace"`
	WidgetID        string            `json:"widgetId"`
	Settings        map[string]string `json:"settings,omitempty"`
}

Controls model

type DateMinMax

type DateMinMax struct {
	Min time.Time `json:"min,omitempty"`
	Max time.Time `json:"max,omitempty"`
}

DateMinMax model

type DateRange

type DateRange struct {
	StartAt string `json:"startAt"`
	EndAt   string `json:"endAt"`
}

DateRange model

type EditorInterface

type EditorInterface struct {
	Sys      *Sys       `json:"sys"`
	Controls []Controls `json:"controls"`
	SideBar  []Sidebar  `json:"sidebar"`
}

EditorInterface model

type EditorInterfacesService

type EditorInterfacesService service

EditorInterfacesService service

func (*EditorInterfacesService) Get

func (service *EditorInterfacesService) Get(ctx context.Context, spaceID, contentTypeID string) (*EditorInterface, error)

Get returns a single EditorInterface

func (*EditorInterfacesService) List

func (service *EditorInterfacesService) List(ctx context.Context, spaceID string, query *Query) (*Collection[EditorInterface], error)

List returns an EditorInterface collection

func (*EditorInterfacesService) Update

func (service *EditorInterfacesService) Update(ctx context.Context, spaceID, contentTypeID string, e *EditorInterface) error

Update updates an editor interface

type Entity

type Entity struct {
	Sys Sys `json:"sys"`
}

Entity model

type EntriesService

type EntriesService service

EntriesService service

func (*EntriesService) Archive

func (service *EntriesService) Archive(ctx context.Context, env *Environment, entry *Entry) error

Archive the entry

func (*EntriesService) Delete

func (service *EntriesService) Delete(ctx context.Context, env *Environment, entryID string) error

Delete the entry

func (*EntriesService) Get

func (service *EntriesService) Get(ctx context.Context, env *Environment, entryID string) (*Entry, error)

Get returns a single entry

func (*EntriesService) List

func (service *EntriesService) List(ctx context.Context, env *Environment, query *Query) (*Collection[Entry], error)

List returns entries collection

func (*EntriesService) Publish

func (service *EntriesService) Publish(ctx context.Context, env *Environment, entry *Entry) error

Publish the entry

func (*EntriesService) Unarchive

func (service *EntriesService) Unarchive(ctx context.Context, env *Environment, entry *Entry) error

Unarchive the entry

func (*EntriesService) Unpublish

func (service *EntriesService) Unpublish(ctx context.Context, env *Environment, entry *Entry) error

Unpublish the entry

func (*EntriesService) Upsert

func (service *EntriesService) Upsert(ctx context.Context, env *Environment, contentTypeID string, e *Entry) error

Upsert updates or creates a new entry

type Entry

type Entry struct {
	Locale string         `json:"locale"`
	Sys    *Sys           `json:"sys"`
	Fields map[string]any `json:"fields"`
}

Entry model

func (*Entry) GetVersion

func (entry *Entry) GetVersion() int

GetVersion returns entity version

type EntrySnapshot

type EntrySnapshot struct {
	Sys                 *Sys                `json:"sys"`
	EntrySnapshotDetail EntrySnapshotDetail `json:"snapshot"`
}

EntrySnapshot model

type EntrySnapshotDetail

type EntrySnapshotDetail struct {
	Fields map[string]interface{} `json:"fields"`
	Sys    *Sys                   `json:"sys"`
}

EntrySnapshotDetail model

type EntryTask

type EntryTask struct {
	Sys        *Sys       `json:"sys"`
	Body       string     `json:"body"`
	Status     string     `json:"status"`
	AssignedTo AssignedTo `json:"assignedTo"`
}

EntryTask model

func (*EntryTask) GetVersion

func (entryTask *EntryTask) GetVersion() int

GetVersion returns entity version

type EntryTasksService

type EntryTasksService service

EntryTasksService service

func (*EntryTasksService) Delete

func (service *EntryTasksService) Delete(ctx context.Context, env *Environment, entryID, entryTaskID string) error

Delete the entry task

func (*EntryTasksService) Get

func (service *EntryTasksService) Get(ctx context.Context, env *Environment, entryID, entryTaskID string) (*EntryTask, error)

Get returns a single entry task

func (*EntryTasksService) List

func (service *EntryTasksService) List(ctx context.Context, env *Environment, entryID string, query *Query) (*Collection[EntryTask], error)

List returns entry tasks collection

func (*EntryTasksService) Upsert

func (service *EntryTasksService) Upsert(ctx context.Context, env *Environment, entryID string, entryTask *EntryTask) error

Upsert updates or creates a new entry task

type Environment

type Environment struct {
	Sys  *Sys   `json:"sys"`
	Name string `json:"name"`
}

Environment model

func (*Environment) GetVersion

func (e *Environment) GetVersion() int

GetVersion returns entity version

type EnvironmentAlias

type EnvironmentAlias struct {
	Sys   *Sys         `json:"sys"`
	Alias *AliasDetail `json:"environment"`
}

EnvironmentAlias model

func (*EnvironmentAlias) GetVersion

func (environmentAlias *EnvironmentAlias) GetVersion() int

GetVersion returns entity version

type EnvironmentAliasesService

type EnvironmentAliasesService service

EnvironmentAliasesService service

func (*EnvironmentAliasesService) Get

func (service *EnvironmentAliasesService) Get(ctx context.Context, spaceID, environmentAliasID string) (*EnvironmentAlias, error)

Get returns a single environment alias entity

func (*EnvironmentAliasesService) List

func (service *EnvironmentAliasesService) List(ctx context.Context, spaceID string, query *Query) (*Collection[EnvironmentAlias], error)

List returns an environment aliases collection

func (*EnvironmentAliasesService) Update

func (service *EnvironmentAliasesService) Update(ctx context.Context, spaceID string, ea *EnvironmentAlias) error

Update updates an environment alias

type EnvironmentLink struct {
	Sys Sys `json:"sys"`
}

EnvironmentLink model

type Environments

type Environments struct {
	Sys Sys `json:"sys,omitempty"`
}

Environments model

type EnvironmentsService

type EnvironmentsService service

EnvironmentsService service

func (*EnvironmentsService) Delete

func (service *EnvironmentsService) Delete(ctx context.Context, spaceID string, e *Environment) error

Delete the environment

func (*EnvironmentsService) Get

func (service *EnvironmentsService) Get(ctx context.Context, spaceID, environmentID string) (*Environment, error)

Get returns a single environment entity

func (*EnvironmentsService) List

func (service *EnvironmentsService) List(ctx context.Context, spaceID string, query *Query) (*Collection[Environment], error)

List returns an environments collection

func (*EnvironmentsService) Upsert

func (service *EnvironmentsService) Upsert(ctx context.Context, spaceID string, e *Environment) error

Upsert updates or creates a new environment

type ErrorDetail

type ErrorDetail struct {
	ID      string      `json:"id,omitempty"`
	Name    string      `json:"name,omitempty"`
	Path    interface{} `json:"path,omitempty"`
	Details string      `json:"details,omitempty"`
	Value   interface{} `json:"value,omitempty"`
}

ErrorDetail model

type ErrorDetails

type ErrorDetails struct {
	Errors []*ErrorDetail `json:"errors,omitempty"`
}

ErrorDetails model

type ErrorResponse

type ErrorResponse struct {
	Sys       *Sys          `json:"sys"`
	Message   string        `json:"message,omitempty"`
	RequestID string        `json:"requestId,omitempty"`
	Details   *ErrorDetails `json:"details,omitempty"`
}

ErrorResponse model

func (ErrorResponse) Error

func (e ErrorResponse) Error() string

type Extension

type Extension struct {
	Sys       *Sys             `json:"sys"`
	Extension ExtensionDetails `json:"extension"`
}

Extension model

func (*Extension) GetVersion

func (extension *Extension) GetVersion() int

GetVersion returns entity version

type ExtensionDetails

type ExtensionDetails struct {
	SRC        string       `json:"src"`
	Name       string       `json:"name"`
	FieldTypes []FieldTypes `json:"fieldTypes"`
	Sidebar    bool         `json:"sidebar"`
}

ExtensionDetails model

type ExtensionsService

type ExtensionsService service

ExtensionsService service

func (*ExtensionsService) Delete

func (service *ExtensionsService) Delete(ctx context.Context, env *Environment, extensionID string) error

Delete the extension

func (*ExtensionsService) Get

func (service *ExtensionsService) Get(ctx context.Context, env *Environment, extensionID string) (*Extension, error)

Get returns a single extension

func (*ExtensionsService) List

func (service *ExtensionsService) List(ctx context.Context, env *Environment, query *Query) (*Collection[Extension], error)

List returns an extensions collection

func (*ExtensionsService) Upsert

func (service *ExtensionsService) Upsert(ctx context.Context, env *Environment, e *Extension) error

Upsert updates or creates a new extension

type Field

type Field struct {
	ID          string              `json:"id,omitempty"`
	Name        string              `json:"name"`
	Type        string              `json:"type"`
	LinkType    string              `json:"linkType,omitempty"`
	Items       *FieldTypeArrayItem `json:"items,omitempty"`
	Required    bool                `json:"required,omitempty"`
	Localized   bool                `json:"localized,omitempty"`
	Disabled    bool                `json:"disabled,omitempty"`
	Omitted     bool                `json:"omitted,omitempty"`
	Validations []FieldValidation   `json:"validations,omitempty"`
}

Field model

func (*Field) UnmarshalJSON

func (field *Field) UnmarshalJSON(data []byte) error

UnmarshalJSON for custom json unmarshaling

type FieldTypeArrayItem

type FieldTypeArrayItem struct {
	Type        string            `json:"type,omitempty"`
	Validations []FieldValidation `json:"validations,omitempty"`
	LinkType    string            `json:"linkType,omitempty"`
}

FieldTypeArrayItem model

func (*FieldTypeArrayItem) UnmarshalJSON

func (item *FieldTypeArrayItem) UnmarshalJSON(data []byte) error

UnmarshalJSON for custom json unmarshaling

type FieldTypes

type FieldTypes struct {
	Type string `json:"type"`
}

FieldTypes model

type FieldValidation

type FieldValidation interface{}

FieldValidation interface

func ParseValidations

func ParseValidations(data []interface{}) (validations []FieldValidation, err error)

ParseValidations converts json representation to go struct

type FieldValidationDate

type FieldValidationDate struct {
	Range        *DateMinMax `json:"dateRange,omitempty"`
	ErrorMessage string      `json:"message,omitempty"`
}

FieldValidationDate model

func (*FieldValidationDate) MarshalJSON

func (v *FieldValidationDate) MarshalJSON() ([]byte, error)

MarshalJSON for custom json marshaling

func (*FieldValidationDate) UnmarshalJSON

func (v *FieldValidationDate) UnmarshalJSON(data []byte) error

UnmarshalJSON for custom json unmarshaling

type FieldValidationDimension

type FieldValidationDimension struct {
	Width        *MinMax `json:"width,omitempty"`
	Height       *MinMax `json:"height,omitempty"`
	ErrorMessage string  `json:"message,omitempty"`
}

FieldValidationDimension model

func (*FieldValidationDimension) MarshalJSON

func (v *FieldValidationDimension) MarshalJSON() ([]byte, error)

MarshalJSON for custom json marshaling

func (*FieldValidationDimension) UnmarshalJSON

func (v *FieldValidationDimension) UnmarshalJSON(data []byte) error

UnmarshalJSON for custom json unmarshaling

type FieldValidationEnabledMarks

type FieldValidationEnabledMarks struct {
	EnabledMarks []string `json:"enabledMarks,omitempty"`
	ErrorMessage string   `json:"message,omitempty"`
}

FieldValidationEnabledMarks model

type FieldValidationEnabledNodeTypes

type FieldValidationEnabledNodeTypes struct {
	EnabledNodeTypes []string `json:"enabledNodeTypes,omitempty"`
	ErrorMessage     string   `json:"message,omitempty"`
}

FieldValidationEnabledNodeTypes model

type FieldValidationFileSize

type FieldValidationFileSize struct {
	Size         *MinMax `json:"assetFileSize,omitempty"`
	ErrorMessage string  `json:"message,omitempty"`
}

FieldValidationFileSize model

type FieldValidationLink struct {
	LinkContentType []string `json:"linkContentType,omitempty"`
}

FieldValidationLink model

type FieldValidationMimeType

type FieldValidationMimeType struct {
	MimeTypes []string `json:"linkMimetypeGroup,omitempty"`
}

FieldValidationMimeType model

type FieldValidationPredefinedValues

type FieldValidationPredefinedValues struct {
	In           []interface{} `json:"in,omitempty"`
	ErrorMessage string        `json:"message"`
}

FieldValidationPredefinedValues model

type FieldValidationRange

type FieldValidationRange struct {
	Range        *MinMax `json:"range,omitempty"`
	ErrorMessage string  `json:"message,omitempty"`
}

FieldValidationRange model

type FieldValidationRegex

type FieldValidationRegex struct {
	Regex        *Regex `json:"regexp,omitempty"`
	ErrorMessage string `json:"message,omitempty"`
}

FieldValidationRegex model

type FieldValidationSize

type FieldValidationSize struct {
	Size         *MinMax `json:"size,omitempty"`
	ErrorMessage string  `json:"message,omitempty"`
}

FieldValidationSize model

type FieldValidationUnique

type FieldValidationUnique struct {
	Unique bool `json:"unique"`
}

FieldValidationUnique model

type File

type File struct {
	URL         string       `json:"url,omitempty"`
	UploadURL   string       `json:"upload,omitempty"`
	UploadFrom  *UploadFrom  `json:"uploadFrom,omitempty"`
	Details     *FileDetails `json:"details,omitempty"`
	FileName    string       `json:"fileName,omitempty"`
	ContentType string       `json:"contentType,omitempty"`
}

File represents a Contentful File

type FileDetails

type FileDetails struct {
	Size  int          `json:"size,omitempty"`
	Image *ImageFields `json:"image,omitempty"`
}

FileDetails model

type HealthDetails

type HealthDetails struct {
	Total   int `json:"total"`
	Healthy int `json:"healthy"`
}

HealthDetails model

type ImageFields

type ImageFields struct {
	Width  int `json:"width,omitempty"`
	Height int `json:"height,omitempty"`
}

ImageFields model

type InvalidQueryError

type InvalidQueryError struct{}

InvalidQueryError error model for invalid query responses

type Locale

type Locale struct {
	Sys *Sys `json:"sys,omitempty"`

	// Locale name
	Name string `json:"name,omitempty"`

	// Language code
	Code string `json:"code,omitempty"`

	// If no content is provided for the locale, the Delivery API will return content in a locale specified below:
	FallbackCode string `json:"fallbackCode,omitempty"`

	// Make the locale as default locale for your account
	Default bool `json:"default,omitempty"`

	// Entries with required fields can still be published if locale is empty.
	Optional bool `json:"optional,omitempty"`

	// Includes locale in the Delivery API response.
	CDA bool `json:"contentDeliveryApi"`

	// Displays locale to editors and enables it in Management API.
	CMA bool `json:"contentManagementApi"`
}

Locale model

func (*Locale) GetVersion

func (locale *Locale) GetVersion() int

GetVersion returns entity version

type LocaleItem

type LocaleItem[T any] struct {
	Item *T
	Map  map[string]T
}

func (LocaleItem[T]) MarshalJSON

func (l LocaleItem[T]) MarshalJSON() ([]byte, error)

func (*LocaleItem[T]) UnmarshalJSON

func (l *LocaleItem[T]) UnmarshalJSON(b []byte) error

type LocalesService

type LocalesService service

LocalesService service

func (*LocalesService) Delete

func (service *LocalesService) Delete(ctx context.Context, spaceID string, locale *Locale) error

Delete the locale

func (*LocalesService) Get

func (service *LocalesService) Get(ctx context.Context, spaceID, localeID string) (*Locale, error)

Get returns a single locale entity

func (*LocalesService) List

func (service *LocalesService) List(ctx context.Context, spaceID string, query *Query) (*Collection[Locale], error)

List returns a locales collection

func (*LocalesService) Upsert

func (service *LocalesService) Upsert(ctx context.Context, spaceID string, locale *Locale) error

Upsert updates or creates a new locale entity

type Locations

type Locations struct {
	Location string `json:"location"`
}

Locations model

type Member

type Member struct {
	Sys *Sys `json:"sys"`
}

Member model

type Membership

type Membership struct {
	Sys   *Sys    `json:"sys"`
	Admin bool    `json:"admin"`
	Roles []Roles `json:"roles"`
	User  Member  `json:"user,omitempty"`
	Email string  `json:"email,omitempty"`
}

Membership model

func (*Membership) GetVersion

func (membership *Membership) GetVersion() int

GetVersion returns entity version

type MembershipsService

type MembershipsService service

MembershipsService service

func (*MembershipsService) Delete

func (service *MembershipsService) Delete(ctx context.Context, spaceID string, membershipID string) error

Delete the role

func (*MembershipsService) Get

func (service *MembershipsService) Get(ctx context.Context, spaceID, membershipID string) (*Membership, error)

Get returns a single membership

func (*MembershipsService) List

func (service *MembershipsService) List(ctx context.Context, spaceID string, query *Query) (*Collection[Membership], error)

List returns membership collection

func (*MembershipsService) Upsert

func (service *MembershipsService) Upsert(ctx context.Context, spaceID string, m *Membership) error

Upsert updates or creates a new membership

type MinMax

type MinMax struct {
	Min float64 `json:"min,omitempty"`
	Max float64 `json:"max,omitempty"`
}

MinMax model

type NotFoundError

type NotFoundError struct {
	APIError
}

NotFoundError for 404 errors

func (NotFoundError) Error

func (e NotFoundError) Error() string

type Organization

type Organization struct {
	Sys  *Sys   `json:"sys"`
	Name string `json:"name"`
}

Organization model

type OrganizationsService

type OrganizationsService service

OrganizationsService service

func (*OrganizationsService) List

func (service *OrganizationsService) List(ctx context.Context, query *Query) (*Collection[Organization], error)

List returns an organizations collection

type Permissions

type Permissions struct {
	ContentModel       []string `json:"ContentModel"`
	Settings           any      `json:"Settings"`
	ContentDelivery    any      `json:"ContentDelivery"`
	Environments       any      `json:"Environments"`
	EnvironmentAliases any      `json:"EnvironmentAliases"`
}

Permissions model

type Policy

type Policy struct {
	Effect     string     `json:"effect"`
	Actions    any        `json:"actions"`
	Constraint Constraint `json:"constraint"`
}

Policy model

type PreviewAPIKey

type PreviewAPIKey struct {
	Sys Sys `json:"sys,omitempty"`
}

PreviewAPIKey model

type Query

type Query struct {
	// contains filtered or unexported fields
}

Query model

func NewQuery

func NewQuery() *Query

NewQuery initializes a new query

func (*Query) All

func (q *Query) All(field string, value []string) *Query

All [all] query

func (*Query) ContentType

func (q *Query) ContentType(ct string) *Query

ContentType query

func (*Query) Equal

func (q *Query) Equal(field string, value interface{}) *Query

Equal equality query

func (*Query) Exists

func (q *Query) Exists(field string) *Query

Exists [exists] query

func (*Query) GreaterThan

func (q *Query) GreaterThan(field string, value interface{}) *Query

GreaterThan [gt] query

func (*Query) GreaterThanOrEqual

func (q *Query) GreaterThanOrEqual(field string, value interface{}) *Query

GreaterThanOrEqual [lte] query

func (*Query) In

func (q *Query) In(field string, value []string) *Query

In [in] query

func (*Query) Include

func (q *Query) Include(include uint16) *Query

Include query

func (*Query) LessThan

func (q *Query) LessThan(field string, value interface{}) *Query

LessThan [lt] query

func (*Query) LessThanOrEqual

func (q *Query) LessThanOrEqual(field string, value interface{}) *Query

LessThanOrEqual [lte] query

func (*Query) Limit

func (q *Query) Limit(limit uint16) *Query

Limit query

func (*Query) Locale

func (q *Query) Locale(locale string) *Query

Locale query

func (*Query) Match

func (q *Query) Match(field, match string) *Query

Match param

func (*Query) MimeType

func (q *Query) MimeType(mime string) *Query

MimeType query

func (*Query) Near

func (q *Query) Near(field string, lat, lon int16) *Query

Near param

func (*Query) NotEqual

func (q *Query) NotEqual(field string, value interface{}) *Query

NotEqual [ne] query

func (*Query) NotExists

func (q *Query) NotExists(field string) *Query

NotExists [exists] query

func (*Query) NotIn

func (q *Query) NotIn(field string, value []string) *Query

NotIn [nin] query

func (*Query) Order

func (q *Query) Order(field string, reverse bool) *Query

Order param

func (*Query) Query

func (q *Query) Query(qStr string) *Query

Query param

func (*Query) Select

func (q *Query) Select(fields []string) *Query

Select query

func (*Query) Skip

func (q *Query) Skip(skip uint16) *Query

Skip query

func (*Query) String

func (q *Query) String() string

func (*Query) Values

func (q *Query) Values() url.Values

Values constructs url.Values

func (*Query) Within

func (q *Query) Within(field string, lat1, lon1, lat2, lon2 int16) *Query

Within param

func (*Query) WithinRadius

func (q *Query) WithinRadius(field string, lat1, lon1, radius int16) *Query

WithinRadius param

type RateLimitExceededError

type RateLimitExceededError struct {
	APIError
}

RateLimitExceededError for rate limit errors

func (RateLimitExceededError) Error

func (e RateLimitExceededError) Error() string

type Regex

type Regex struct {
	Pattern string `json:"pattern,omitempty"`
	Flags   string `json:"flags,omitempty"`
}

Regex model

type Request

type Request struct {
	URL     string            `json:"url"`
	Method  string            `json:"method"`
	Headers map[string]string `json:"headers"`
	Body    string            `json:"body"`
}

Request model

type Resource

type Resource struct {
	Sys *Sys `json:"sys"`
}

Resource model

type ResourcesService

type ResourcesService service

ResourcesService service

func (*ResourcesService) Create

func (service *ResourcesService) Create(ctx context.Context, spaceID, filePath string) error

Create creates an upload resource

func (*ResourcesService) Delete

func (service *ResourcesService) Delete(ctx context.Context, spaceID, resourceID string) error

Delete the resource

func (*ResourcesService) Get

func (service *ResourcesService) Get(ctx context.Context, spaceID, resourceID string) (*Resource, error)

Get returns a single resource/upload

type Response

type Response struct {
	URL        string            `json:"url"`
	Headers    map[string]string `json:"headers"`
	Body       string            `json:"body"`
	StatusCode int               `json:"statusCode"`
}

Response model

type Role

type Role struct {
	Sys         *Sys        `json:"sys"`
	Name        string      `json:"name"`
	Description string      `json:"description"`
	Policies    []Policy    `json:"policies"`
	Permissions Permissions `json:"permissions"`
}

Role model

func (*Role) GetVersion

func (r *Role) GetVersion() int

GetVersion returns entity version

type Roles

type Roles struct {
	Sys *Sys `json:"sys"`
}

Roles model

type RolesService

type RolesService service

RolesService service

func (*RolesService) Delete

func (service *RolesService) Delete(ctx context.Context, spaceID string, roleID string) error

Delete the role

func (*RolesService) Get

func (service *RolesService) Get(ctx context.Context, spaceID, roleID string) (*Role, error)

Get returns a single role

func (*RolesService) List

func (service *RolesService) List(ctx context.Context, spaceID string, query *Query) (*Collection[Role], error)

List returns an environments collection

func (*RolesService) Upsert

func (service *RolesService) Upsert(ctx context.Context, spaceID string, r *Role) error

Upsert updates or creates a new role

type ScheduledAction

type ScheduledAction struct {
	Sys          *Sys              `json:"sys"`
	Entity       Entity            `json:"entity"`
	Environment  EnvironmentLink   `json:"environment"`
	ScheduledFor map[string]string `json:"scheduledFor"`
	Action       string            `json:"action"`
}

ScheduledAction model

func (*ScheduledAction) GetVersion

func (scheduledAction *ScheduledAction) GetVersion() int

GetVersion returns entity version

type ScheduledActionsService

type ScheduledActionsService service

ScheduledActionsService service

func (*ScheduledActionsService) Create

func (service *ScheduledActionsService) Create(ctx context.Context, spaceID, entryID string, scheduledAction *ScheduledAction) error

Create creates a new scheduled actions

func (*ScheduledActionsService) Delete

func (service *ScheduledActionsService) Delete(ctx context.Context, spaceID, entryID, scheduledActionID string) error

Delete the scheduled action

func (*ScheduledActionsService) List

func (service *ScheduledActionsService) List(ctx context.Context, spaceID, entryID string, query *Query) (*Collection[ScheduledAction], error)

List returns scheduled actions collection

type ServerError

type ServerError struct{}

ServerError error model for server error responses

type Sidebar struct {
	WidgetNameSpace string            `json:"widgetNamespace"`
	WidgetID        string            `json:"widgetId"`
	Settings        map[string]string `json:"settings,omitempty"`
	Disabled        bool              `json:"disabled"`
}

Sidebar model

type SnapshotsService

type SnapshotsService service

SnapshotsService service

func (*SnapshotsService) GetContentTypeSnapshots

func (service *SnapshotsService) GetContentTypeSnapshots(ctx context.Context, spaceID, contentTypeID, snapshotID string) (*ContentTypeSnapshot, error)

GetContentTypeSnapshots returns a single snapshot of an entry

func (*SnapshotsService) GetEntrySnapshot

func (service *SnapshotsService) GetEntrySnapshot(ctx context.Context, spaceID, entryID, snapshotID string) (*EntrySnapshot, error)

GetEntrySnapshot returns a single snapshot of an entry

func (*SnapshotsService) ListContentTypeSnapshots

func (service *SnapshotsService) ListContentTypeSnapshots(ctx context.Context, spaceID, contentTypeID string, query *Query) (*Collection[ContentTypeSnapshot], error)

ListContentTypeSnapshots returns snapshot collection

func (*SnapshotsService) ListEntrySnapshots

func (service *SnapshotsService) ListEntrySnapshots(ctx context.Context, spaceID, entryID string, query *Query) (*Collection[EntrySnapshot], error)

ListEntrySnapshots returns snapshot collection

type Space

type Space struct {
	Sys           *Sys   `json:"sys,omitempty"`
	Name          string `json:"name,omitempty"`
	DefaultLocale string `json:"defaultLocale,omitempty"`
}

Space model

func (*Space) GetVersion

func (space *Space) GetVersion() int

GetVersion returns entity version

func (*Space) MarshalJSON

func (space *Space) MarshalJSON() ([]byte, error)

MarshalJSON for custom json marshaling

type SpacesService

type SpacesService service

SpacesService model

func (*SpacesService) Delete

func (service *SpacesService) Delete(ctx context.Context, space *Space) error

Delete the given space

Example
cma := NewCMA("cma-token")

space, err := cma.Spaces.Get(context.Background(), "space-id")
if err != nil {
	log.Fatal(err)
}

err = cma.Spaces.Delete(context.Background(), space)
if err != nil {
	log.Fatal(err)
}
Output:

Example (All)
cma := NewCMA("cma-token")

collection, err := cma.Spaces.List(context.Background(), nil)
if err != nil {
	log.Fatal(err)
}

for _, space := range collection.Items {
	err := cma.Spaces.Delete(context.Background(), &space)
	if err != nil {
		log.Fatal(err)
	}
}
Output:

func (*SpacesService) Get

func (service *SpacesService) Get(ctx context.Context, spaceID string) (*Space, error)

Get returns a single space entity

Example
cma := NewCMA("cma-token")

space, err := cma.Spaces.Get(context.Background(), "space-id")
if err != nil {
	log.Fatal(err)
}

fmt.Println(space.Name)
Output:

func (*SpacesService) List

func (service *SpacesService) List(ctx context.Context, query *Query) (*Collection[Space], error)

List creates a spaces collection

Example
cma := NewCMA("cma-token")
collection, err := cma.Spaces.List(context.Background(), nil)
if err != nil {
	log.Fatal(err)
}

spaces := collection.Items
for _, space := range spaces {
	fmt.Println(space.Sys.ID, space.Name)
}
Output:

func (*SpacesService) Upsert

func (service *SpacesService) Upsert(ctx context.Context, space *Space) error

Upsert updates or creates a new space

Example (Create)
cma := NewCMA("cma-token")

space := &Space{
	Name:          "space-name",
	DefaultLocale: "en-US",
}

err := cma.Spaces.Upsert(context.Background(), space)
if err != nil {
	log.Fatal(err)
}
Output:

Example (Update)
cma := NewCMA("cma-token")

space, err := cma.Spaces.Get(context.Background(), "space-id")
if err != nil {
	log.Fatal(err)
}

space.Name = "modified"
err = cma.Spaces.Upsert(context.Background(), space)
if err != nil {
	log.Fatal(err)
}
Output:

type Sys

type Sys struct {
	ID               string       `json:"id,omitempty"`
	Type             string       `json:"type,omitempty"`
	LinkType         string       `json:"linkType,omitempty"`
	CreatedAt        string       `json:"createdAt,omitempty"`
	UpdatedAt        string       `json:"updatedAt,omitempty"`
	UpdatedBy        *Sys         `json:"updatedBy,omitempty"`
	Version          int          `json:"version,omitempty"`
	Revision         int          `json:"revision,omitempty"`
	ContentType      *ContentType `json:"contentType,omitempty"`
	Space            *Space       `json:"space,omitempty"`
	FirstPublishedAt string       `json:"firstPublishedAt,omitempty"`
	PublishedCounter int          `json:"publishedCounter,omitempty"`
	PublishedAt      string       `json:"publishedAt,omitempty"`
	PublishedBy      *Sys         `json:"publishedBy,omitempty"`
	PublishedVersion int          `json:"publishedVersion,omitempty"`
	ArchivedAt       string       `json:"archivedAt,omitempty"`
	ArchivedBy       *Sys         `json:"archivedBy,omitempty"`
	ArchivedVersion  int          `json:"archivedVersion,omitempty"`
}

Sys model

type UploadFrom

type UploadFrom struct {
	Sys *Sys `json:"sys,omitempty"`
}

UploadFrom model

type Usage

type Usage struct {
	Sys           *Sys           `json:"sys"`
	UnitOfMeasure string         `json:"unitOfMeasure"`
	Metric        string         `json:"metric"`
	DateRange     DateRange      `json:"dateRange"`
	TotalUsage    int            `json:"usage"`
	UsagePerDay   map[string]int `json:"usagePerDay"`
}

Usage model

type UsagesService

type UsagesService service

UsagesService service

func (*UsagesService) GetOrganizationUsage

func (service *UsagesService) GetOrganizationUsage(ctx context.Context, organizationID, orderBy, metric, startAt, endAt string, query *Query) (*Collection[Usage], error)

GetOrganizationUsage returns the usage of the specified organization

func (*UsagesService) GetSpaceUsage

func (service *UsagesService) GetSpaceUsage(ctx context.Context, organizationID, orderBy, metric, startAt, endAt string, query *Query) (*Collection[Usage], error)

GetSpaceUsage returns the organization usage by space

type User

type User struct {
	Sys                            *Sys   `json:"sys,omitempty"`
	FirstName                      string `json:"firstName"`
	LastName                       string `json:"lastName"`
	AvatarURL                      string `json:"avatarUrl"`
	Email                          string `json:"email"`
	Activated                      bool   `json:"activated"`
	SignInCount                    int    `json:"signInCount"`
	Confirmed                      bool   `json:"confirmed"`
	TwoFactorAuthenticationEnabled bool   `json:"2faEnabled"`
}

User model

type UsersService

type UsersService service

UsersService service

func (*UsersService) Me

func (service *UsersService) Me(ctx context.Context) (*User, error)

Me returns current authenticated user

type ValidationFailedError

type ValidationFailedError struct {
	APIError
}

ValidationFailedError model

func (ValidationFailedError) Error

func (e ValidationFailedError) Error() string

type VersionMismatchError

type VersionMismatchError struct {
	APIError
}

VersionMismatchError for 409 errors

func (VersionMismatchError) Error

func (e VersionMismatchError) Error() string

type Webhook

type Webhook struct {
	Sys               *Sys             `json:"sys,omitempty"`
	Name              string           `json:"name,omitempty"`
	URL               string           `json:"url,omitempty"`
	Topics            []string         `json:"topics,omitempty"`
	HTTPBasicUsername string           `json:"httpBasicUsername,omitempty"`
	HTTPBasicPassword string           `json:"httpBasicPassword,omitempty"`
	Headers           []*WebhookHeader `json:"headers,omitempty"`
}

Webhook model

func (*Webhook) GetVersion

func (webhook *Webhook) GetVersion() int

GetVersion returns entity version

type WebhookCall

type WebhookCall struct {
	Sys        *Sys     `json:"sys"`
	Request    Request  `json:"request,omitempty"`
	Response   Response `json:"response,omitempty"`
	StatusCode int      `json:"statusCode"`
	Errors     []string `json:"errors"`
	EventType  string   `json:"eventType"`
	URL        string   `json:"url"`
	RequestAt  string   `json:"requestAt"`
	ResponseAt string   `json:"responseAt"`
}

WebhookCall model

type WebhookCallsService

type WebhookCallsService service

WebhookCallsService service

func (*WebhookCallsService) Get

func (service *WebhookCallsService) Get(ctx context.Context, spaceID, webhookID, callID string) (*WebhookCall, error)

Get returns details of a single webhook call

func (*WebhookCallsService) Health

func (service *WebhookCallsService) Health(ctx context.Context, spaceID, webhookID string) (*WebhookHealth, error)

Health returns the health of a webhook

func (*WebhookCallsService) List

func (service *WebhookCallsService) List(ctx context.Context, spaceID, webhookID string, query *Query) (*Collection[WebhookCall], error)

List returns a webhook calls collection

type WebhookHeader

type WebhookHeader struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

WebhookHeader model

type WebhookHealth

type WebhookHealth struct {
	Sys   *Sys          `json:"sys"`
	Calls HealthDetails `json:"calls"`
}

WebhookHealth model

type WebhooksService

type WebhooksService service

WebhooksService service

func (*WebhooksService) Delete

func (service *WebhooksService) Delete(ctx context.Context, spaceID string, webhook *Webhook) error

Delete the webhook

func (*WebhooksService) Get

func (service *WebhooksService) Get(ctx context.Context, spaceID, webhookID string) (*Webhook, error)

Get returns a single webhook entity

func (*WebhooksService) List

func (service *WebhooksService) List(ctx context.Context, spaceID string, query *Query) (*Collection[Webhook], error)

List returns webhooks collection

func (*WebhooksService) Upsert

func (service *WebhooksService) Upsert(ctx context.Context, spaceID string, webhook *Webhook) error

Upsert updates or creates a new entity

Jump to

Keyboard shortcuts

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