goprismic

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

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

Go to latest
Published: Nov 11, 2014 License: MIT Imports: 11 Imported by: 6

README

goprismic

Build Status

Prismic.io client kit for Go

This client is currently used in production on http://www.socloz.com.

Go 1.3 is required.

Usage

// start api with the default config (3 workers, 5 seconds timeout on requests)
api, err := goprismic.Get("https://myrepo.prismic.io/api", "repo key", goprismic.DefaultConfig)

docs, err := api.Master().Form("everything").Query("[[:d = at(document.tags, [\"Featured\"])]]").Order("my.product.name", goprismic.OrderAsc).Page(1).Submit()
if err != nil {
	// handle error
}
if len(docs) == 0 {
	// nothing found
}
doc := docs[0]

st, found := doc.GetStructuredTextFragment("content")
if found {
	fmt.Println(st.AsHtml())
}

You have to resolve document links using a user-supplied link resolver :

r := func(l link.Link) string {
	return l.(*link.DocumentLink).Document.Slug
}

and resolve links at document/fragment/block level :

doc.ResolveLinks(r)

st, _ := doc.GetStructuredTextFragment("content")
st.ResolveLinks(r)

p, _ := st.GetFirstParagraph()
p.ResolveLinks(r)

Proxy

A simple asynchronous caching proxy is included.

// Up to 1000 documents will be cached.
proxy, err := proxy.New("https://myrepo.prismic.io/api", "repo key", goprismic.DefaultConfig, proxy.Config{CacheSize: 1000})

// Not cached
docs, err := proxy.Direct().Master().Form("everything").Submit()

// Cached
doc, err := proxy.GetDocument(id)

// Cached
doc, err := proxy.GetDocumentBy("product", "fieldname", "fieldvalue")

// Cached
doc, err := proxy.GetDocumentBy("product", "fieldname", "fieldvalue")

// Cached
res, err := proxy.Search().Form("menu").PageSize(200).Submit()

When a document is updated :

  • between "update time" and "update time + TTL", documents are asynchronously refreshed (if a document is accessed, the cached version is returned, and the cache is asynchronously updated),
  • after "update time + TTL", documents are fetched directly from prismic (cache miss).

If no ttl is set, refreshes are always asynchronous.

You can define :

  • a refresh chance (between 0 and 1) - only a fraction of contents will be refreshed at a time, ensuring that prismic is not flooded after an update,
  • a master refresh interval - the proxy will check for updates at the defined frequency.

The proxy will try to avoid flooding prismic by automatically lower/raise the refresh chance.

Workers

Access to the prismic api is done using workers, limiting the number of simultaneous connexions to the API.

See http://godoc.org/github.com/SoCloz/goprismic for the api documentation and http://godoc.org/github.com/SoCloz/goprismic/proxy for the proxy documentation.

Blog post : http://techblog.socloz.com/2013/11/introducing-goprismic-a-prismic-io-go-client-kit/

License

This bundle is released under the MIT license (see LICENSE).

Documentation

Index

Constants

View Source
const (
	StatusOK = iota
	StatusOverCapacity
)
View Source
const (
	OrderAsc = iota
	OrderDesc
)

Variables

View Source
var DefaultConfig = Config{
	Workers: 3,
	Timeout: 5 * time.Second,
}

Default configuration

Functions

This section is empty.

Types

type Api

type Api struct {
	URL         string
	AccessToken string
	Data        ApiData

	Config Config

	Status int
	// contains filtered or unexported fields
}

func Get

func Get(u, accessToken string, cfg Config) (*Api, error)

Api entry point Use Get(url, accessToken, DefaultConfig) to use the default config

func (*Api) GetMasterRef

func (a *Api) GetMasterRef() string

Returns the master ref

func (*Api) Master

func (a *Api) Master() *SearchForm

Fetches the master ref

func (*Api) Ref

func (a *Api) Ref(label string) *SearchForm

Fetch another ref

func (*Api) Refresh

func (a *Api) Refresh() error

Refreshes the Api data

type ApiData

type ApiData struct {
	Forms         map[string]Form   `json:"forms"`
	Refs          []Ref             `json:"refs"`
	Bookmarks     map[string]string `json:"bookmarks"`
	Tags          []string          `json:"tags"`
	Types         map[string]string `json:"types"`
	OAuthInitiate string            `json:"oauth_initiate"`
	OAuthToken    string            `json:"oauth_token"`
}

type Config

type Config struct {
	// Number of workers (simultaneous connections)
	Workers int
	// Timeout for HTTP requests
	Timeout time.Duration
	// Debug mode
	Debug bool
}

type Document

type Document struct {
	Id        string        `json:"id"`
	Type      string        `json:"type"`
	Href      string        `json:"href"`
	Tags      []string      `json:"tags"`
	Slugs     []string      `json:"slugs"`
	Fragments fragment.Tree `json:"data"`
}

A document is made of fragments of various types

func (*Document) GetBool

func (d *Document) GetBool(field string) (bool, bool)

Returns the boolean representation of a fragment (the first found)

func (*Document) GetColor

func (d *Document) GetColor(field string) (string, bool)

Returns a color value (the first found)

func (*Document) GetColorFragment

func (d *Document) GetColorFragment(field string) (*fragment.Color, bool)

Returns a color fragment (the first found)

func (*Document) GetDate

func (d *Document) GetDate(field string) (time.Time, bool)

Returns a date value (the first found)

func (*Document) GetDateFragment

func (d *Document) GetDateFragment(field string) (*fragment.Date, bool)

Returns a date fragment (the first found)

func (*Document) GetFragment

func (d *Document) GetFragment(field string) (fragment.Interface, bool)

Returns the first fragment of a certain name

func (*Document) GetFragmentAt

func (d *Document) GetFragmentAt(field string, index int) (fragment.Interface, bool)

Returns the nth fragment of a certain name

func (*Document) GetFragments

func (d *Document) GetFragments(field string) (fragment.List, bool)

Returns the list of fragments of a certain name

func (*Document) GetGeoPointFragment

func (d *Document) GetGeoPointFragment(field string) (*fragment.GeoPoint, bool)

Returns a geopoint fragment (returns the first found)

func (*Document) GetImageFragment

func (d *Document) GetImageFragment(field string) (*fragment.Image, bool)

Returns an image fragment (the first found)

func (*Document) GetLinkFragment

func (d *Document) GetLinkFragment(field string) (*fragment.Link, bool)

Returns a link fragment (the first found)

func (*Document) GetNumber

func (d *Document) GetNumber(field string) (float64, bool)

Returns a number value (the first found)

func (*Document) GetNumberFragment

func (d *Document) GetNumberFragment(field string) (*fragment.Number, bool)

Returns a number fragment (the first found)

func (*Document) GetSlug

func (d *Document) GetSlug() string

Returns the document slug

func (*Document) GetStructuredTextBlocks

func (d *Document) GetStructuredTextBlocks(field string) ([]block.Block, bool)

Returns the list of blocks of a structured text fragment

func (*Document) GetStructuredTextFragment

func (d *Document) GetStructuredTextFragment(field string) (*fragment.StructuredText, bool)

Returns a structured text fragment (returns the first found)

func (*Document) GetText

func (d *Document) GetText(field string) (string, bool)

Returns a text value (the first found)

func (*Document) GetTextFragment

func (d *Document) GetTextFragment(field string) (*fragment.Text, bool)

Returns a text fragment (the first found)

func (*Document) HasSlug

func (d *Document) HasSlug(slug string) bool

Tests if the document has a slug

func (d *Document) ResolveLinks(r link.Resolver)

Resolves links

type Field

type Field struct {
	Type    string `json:"type"`
	Default string `json:"default"`
}

A form field

type Form

type Form struct {
	Name    string           `json:"name"`
	Method  string           `json:"method"`
	Rel     string           `json:"rel"`
	EncType string           `json:"enctype"`
	Action  string           `json:"action"`
	Fields  map[string]Field `json:"fields"`
}

A form

type PrismicError

type PrismicError struct {
	Message string `json:"message"`
	Type    string `json:"type"`
	Line    int    `json:"line"`
	Column  int    `json:"column"`
	Until   int64  `json:"until"`
}

func (*PrismicError) Error

func (e *PrismicError) Error() string

func (*PrismicError) IsOverCapacity

func (e *PrismicError) IsOverCapacity() bool

type Ref

type Ref struct {
	Id          string `json:"id"`
	Ref         string `json:"ref"`
	Label       string `json:"label"`
	IsMasterRef bool   `json:"isMasterRef"`
	ScheduledAt int64  `json:"scheduledAt"`
}

func (*Ref) ScheduledTime

func (r *Ref) ScheduledTime() *time.Time

type SearchForm

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

func (*SearchForm) Data

func (s *SearchForm) Data(data map[string]string) *SearchForm

Adds form data

func (*SearchForm) Error

func (s *SearchForm) Error() error

Returns the error

func (*SearchForm) Form

func (s *SearchForm) Form(name string) *SearchForm

Selects the form on which to use

func (*SearchForm) Order

func (s *SearchForm) Order(field string, order int) *SearchForm

Order result - can be chained multiple times

example : form.Order("my.product.name", OrderAsc).Order("my.product.size", OrderDesc)

func (*SearchForm) Page

func (s *SearchForm) Page(page int) *SearchForm

Sets the page number

func (*SearchForm) PageSize

func (s *SearchForm) PageSize(pageSize int) *SearchForm

Sets the page size

func (*SearchForm) Query

func (s *SearchForm) Query(query string) *SearchForm

Query the form using a predicate query ([[:d = any(document.type, ["article"])]])

func (*SearchForm) Submit

func (s *SearchForm) Submit() (*SearchResult, error)

Searches the repository

type SearchResult

type SearchResult struct {
	Page           int        `json:"page"`
	TotalPages     int        `json:"total_pages"`
	ResultsPerPage int        `json:"results_per_page"`
	TotalResults   int        `json:"total_results_size"`
	Results        []Document `json:"results"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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