typeform

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

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

Go to latest
Published: May 17, 2020 License: MIT Imports: 9 Imported by: 0

README

typeform-go

Non-official Go library for the Typeform API. https://developer.typeform.com/

Installation

go get github.com/marotpam/typeform-go

Basic usage

// create a typeform client with a personal access token (see https://developer.typeform.com/get-started/personal-access-token/)
tfClient := typeform.NewDefaultClient("personalAccessToken")
svc := typeform.NewFormService(tfClient)

// create a new form
f, err := svc.Create(typeform.Form{
  Title: "a form created with typeform-go",
  Fields: []*typeform.Field{
    {
      Title: "do you like go?",
      Type:  typeform.FieldTypeYesNo,
    },
  },
})
if err != nil {
  log.Fatal(err)
}
log.Printf("typeform with id %s created\n", f.ID)

// retrieve an existing form
f, err = svc.Retrieve(f.ID)
if err != nil {
  log.Fatal(err)
}
log.Printf("typeform with id '%s' retrieved successfully\n", f.ID)

// update an existing form
f.Title = "updated form title"
f, err = svc.Update(f)
if err != nil {
  log.Fatal(err)
}
log.Printf("typeform's title is now '%s'\n", f.Title)

// list available forms filtered by params
l, err := svc.List(typeform.FormListParams{
  Search:      "form title",
  Page:        1,
  PageSize:    1,
  WorkspaceID: "workspaceID",
})
if err != nil {
  log.Fatal(err)
}
log.Printf("total number of forms: %d\n", l.TotalItems)

// delete an existing form
err = svc.Delete(f.ID)
if err != nil {
  log.Fatal(err)
}
log.Printf("typeform with id %s successfully deleted\n", f.ID)

Documentation

Index

Constants

View Source
const (
	CodeAuthenticationFailed = "AUTHENTICATION_FAILED"
	CodeFormNotFound         = "FORM_NOT_FOUND"
	CodeImageNotFound        = "IMAGE_NOT_FOUND"
	CodeThemeNotFound        = "THEME_NOT_FOUND"
	CodeWorkspaceNotFound    = "WORKSPACE_NOT_FOUND"
)
View Source
const (
	FieldTypeYesNo          = "yes_no"
	FieldTypeShortText      = "short_text"
	FieldTypeMultipleChoice = "multiple_choice"
	FieldTypePictureChoice  = "picture_choice"
	FieldTypeGroup          = "group"
	FieldTypeEmail          = "email"
	FieldTypeDropdown       = "dropdown"
	FieldTypeLongText       = "long_text"
	FieldTypeFileUpload     = "file_upload"
	FieldTypeNumber         = "number"
	FieldTypeWebsite        = "website"
	FieldTypeLegal          = "legal"
	FieldTypeDate           = "date"
	FieldTypeRating         = "rating"
	FieldTypeStatement      = "statement"
	FieldTypePayment        = "payment"
	FieldTypeOpinionScale   = "opinion_scale"
	FieldTypePhoneNumber    = "phone_number"
)
View Source
const (
	ImageFormatImage      = "image"
	ImageFormatChoice     = "choice"
	ImageFormatBackground = "background"

	ImageSizeDefault        = "default"
	ImageSizeMobile         = "mobile"
	ImageSizeSuperMobile    = "supermobile"
	ImageSizeSuperMobileFit = "supermobilefit"
	ImageSizeSuperSize      = "supersize"
	ImageSizeSuperSizeFit   = "supersizefit"
	ImageSizeSuperTablet    = "supertablet"
	ImageSizeTablet         = "tablet"
	ImageSizeThumbnail      = "thumbnail"
)

Variables

This section is empty.

Functions

func NoBackoff

func NoBackoff(try int) time.Duration

NoBackoff is the no-op implementation of BackoffDuration. This means that there will be no pause between retries, which is not recommended for production usage.

func TwoSecondsIncrementBackoff

func TwoSecondsIncrementBackoff(try int) time.Duration

TwoSecondsIncrementBackoff will retry after increases of 2 seconds between retries (2 seconds after first try, 4 seconds after the second, and so forth)

Types

type Attachment

type Attachment struct {
	Type       string                `json:"type"`
	Href       string                `json:"href"`
	Scale      float64               `json:"scale,omitempty"`
	Properties *attachmentProperties `json:"FieldProperties,omitempty"`
}

type Background

type Background struct {
	Brightness float64 `json:"brightness,omitempty"`
	ImageID    int     `json:"image_id,omitempty"`
	Layout     string  `json:"layout,omitempty"`
}

type BackoffDuration

type BackoffDuration func(try int) time.Duration

BackoffDuration will determine for how long the client should wait before retrying a request after a given `try`.

type Client

type Client struct {
	// AccessToken to access the typeform API.
	AccessToken string
	// HttpClient that will be used to do http calls to the API.
	HttpClient http.Client
	// BaseURL is the base URL to be used in all requests to the API.
	BaseURL url.URL
	// MaxRetries is the maximum number of retries that will be done to the API on transient errors.
	MaxRetries int
	// BackoffDuration is the duration off the backoff period between retries.
	BackoffDuration BackoffDuration
}

client will be used to interact with the typeform API.

func NewClient

func NewClient(token string, c Config) (Client, error)

NewClient will return a default client with values overridden by the provided config.

func NewDefaultClient

func NewDefaultClient(accessToken string) Client

NewDefaultClient will return a production client will all its config values set to defaults.

func (Client) Do

func (c Client) Do(req *http.Request, v interface{}) error

Do will do a request to the typeform API, and unmarshal its response into v. An error will be returned upon failure.

type Colors

type Colors struct {
	Answer     string `json:"answer,omitempty"`
	Background string `json:"background,omitempty"`
	Button     string `json:"button,omitempty"`
	Question   string `json:"question,omitempty"`
}

type Config

type Config struct {
	// BaseAddress is the base address of the API, which can be configured to point to fake implementations of the
	// API for testing purposes. Defaults to https://api.typeform.com
	BaseAddress string
	// HttpTimeoutSeconds is the timeout to be used in http calls to the API, 30 seconds by default.
	HttpTimeoutSeconds int
	// MaxRetries is the maximum number of retries that will be done to the API on transient errors, 5 by default.
	MaxRetries int
	// BackoffDuration is the duration off the backoff period between retries, defaults to TwoSecondsIncrementBackoff.
	BackoffDuration BackoffDuration
	// HttpClient can be used to override the HTTP client that will calls to the typeform API, defaults
	// to http.DefaultClient with a Timeout of 30seconds. Setting it will override HttpTimeoutSeconds.
	HttpClient *http.Client
}

type CreateImageParams

type CreateImageParams struct {
	Image    string `json:"image,omitempty"`
	FileName string `json:"file_name"`
	Url      string `json:"url,omitempty"`
}

type Error

type Error struct {
	URL         string
	Method      string
	StatusCode  int
	Code        string `json:"code"`
	Description string `json:"description"`
}

func (Error) Error

func (e Error) Error() string

type Field

type Field struct {
	ID          string            `json:"id,omitempty"`
	Ref         string            `json:"ref,omitempty"`
	Title       string            `json:"title"`
	Properties  *FieldProperties  `json:"properties,omitempty"`
	Validations *FieldValidations `json:"validations,omitempty"`
	Type        string            `json:"type"`
	Attachment  *Attachment       `json:"attachment,omitempty"`
	Layout      *Layout           `json:"Layout,omitempty"`
}

type FieldChoice

type FieldChoice struct {
	ID         string      `json:"id,omitempty"`
	Ref        string      `json:"ref,omitempty"`
	Label      string      `json:"label"`
	Attachment *Attachment `json:"attachment,omitempty"`
}

type FieldProperties

type FieldProperties struct {
	Description            string          `json:"description,omitempty"`
	ButtonText             string          `json:"button_text,omitempty"`
	Randomize              *bool           `json:"randomize,omitempty"`
	AllowMultipleSelection *bool           `json:"allow_multiple_selection,omitempty"`
	AllowOtherChoice       *bool           `json:"allow_other_choice,omitempty"`
	VerticalAlignment      *bool           `json:"vertical_alignment,omitempty"`
	Supersized             *bool           `json:"supersized,omitempty"`
	ShowLabels             *bool           `json:"show_labels,omitempty"`
	ShowButton             *bool           `json:"show_button,omitempty"`
	AlphabeticalOrder      *bool           `json:"alphabetical_order,omitempty"`
	HideMarks              *bool           `json:"hide_marks,omitempty"`
	StartAtOne             *bool           `json:"start_at_one,omitempty"`
	Choices                *[]*FieldChoice `json:"choices,omitempty"`
	Fields                 []*Field        `json:"fields,omitempty"`
	Separator              string          `json:"separator,omitempty"`
	Structure              string          `json:"structure,omitempty"`
	Shape                  string          `json:"shape,omitempty"`
	DefaultCountryCode     string          `json:"default_country_code,omitempty"`
	Currency               string          `json:"currency,omitempty"`
	Steps                  int             `json:"steps,omitempty"`
	Price                  *Price          `json:"price,omitempty"`
	Labels                 *PropertyLabels `json:"labels,omitempty"`
}

type FieldValidations

type FieldValidations struct {
	Required     bool `json:"required"`
	MaxLength    *int `json:"max_length,omitempty"`
	MinSelection *int `json:"min_selection,omitempty"`
	MaxSelection *int `json:"max_selection,omitempty"`
	MinValue     *int `json:"min_value,omitempty"`
	MaxValue     *int `json:"max_value,omitempty"`
}

type FocalPoint

type FocalPoint struct {
	X float64 `json:"x"`
	Y float64 `json:"y"`
}

type Form

type Form struct {
	ID              string                 `json:"id,omitempty"`
	Title           string                 `json:"title"`
	Workspace       *Link                  `json:"workspace,omitempty"`
	Theme           *Link                  `json:"theme,omitempty"`
	Settings        *Settings              `json:"settings,omitempty"`
	ThankyouScreens []*ThankYouScreen      `json:"thankyou_screens,omitempty"`
	WelcomeScreens  []*WelcomeScreen       `json:"welcome_screens,omitempty"`
	Fields          []*Field               `json:"fields,omitempty"`
	Hidden          []string               `json:"hidden,omitempty"`
	Variables       map[string]interface{} `json:"variables,omitempty"`
	Logic           []*Logic               `json:"logic,omitempty"`
	Outcome         *Outcome               `json:"outcome,omitempty"`
	Links           *FormLinks             `json:"_links,omitempty"`
}
type FormLinks struct {
	Display string `json:"display"`
}

type FormList

type FormList struct {
	TotalItems int            `json:"total_items"`
	PageCount  int            `json:"page_count"`
	Items      []FormListItem `json:"items"`
}

type FormListItem

type FormListItem struct {
	ID            string    `json:"id"`
	Title         string    `json:"title"`
	LastUpdatedAt time.Time `json:"last_updated_at"`
	Self          struct {
		Href string `json:"href"`
	} `json:"self"`
	Theme struct {
		Href string `json:"href"`
	} `json:"theme"`
	Links struct {
		Display string `json:"display"`
	} `json:"_links"`
}

type FormListParams

type FormListParams struct {
	Search      string `url:"search,omitempty"`
	Page        int    `url:"page,omitempty"`
	PageSize    int    `url:"page_size,omitempty"`
	WorkspaceID string `url:"workspace_id,omitempty"`
}

type FormService

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

func NewFormService

func NewFormService(client Client) *FormService

func (FormService) Create

func (s FormService) Create(f Form) (Form, error)

func (FormService) Delete

func (s FormService) Delete(formID string) error

func (FormService) List

func (FormService) Retrieve

func (s FormService) Retrieve(formID string) (Form, error)

func (FormService) Update

func (s FormService) Update(f Form) (Form, error)

type Forms

type Forms struct {
	Count int    `json:"count,omitempty"`
	Href  string `json:"href"`
}

type Image

type Image struct {
	ID        string `json:"id,omitempty"`
	Src       string `json:"src,omitempty"`
	FileName  string `json:"file_name,omitempty"`
	Width     int    `json:"width,omitempty"`
	Height    int    `json:"height,omitempty"`
	MediaType string `json:"media_type,omitempty"`
	HasAlpha  bool   `json:"has_alpha,omitempty"`
	AvgColor  string `json:"avg_color,omitempty"`
}

type ImageList

type ImageList []ImageListItem

type ImageListItem

type ImageListItem struct {
	ID       string `json:"id"`
	Src      string `json:"src"`
	FileName string `json:"file_name"`
}

type ImageService

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

func NewImageService

func NewImageService(client Client) *ImageService

func (ImageService) Create

func (s ImageService) Create(p CreateImageParams) (Image, error)

func (ImageService) Delete

func (s ImageService) Delete(imageID string) error

func (ImageService) List

func (s ImageService) List() (ImageList, error)

func (ImageService) Retrieve

func (s ImageService) Retrieve(imageID string) (Image, error)

func (ImageService) RetrieveFormat

func (s ImageService) RetrieveFormat(imageID, format, size string) (Image, error)

type Layout

type Layout struct {
	Type       string     `json:"type"`
	Attachment Attachment `json:"Attachment"`
}
type Link struct {
	Href string `json:"href,omitempty"`
}

type Logic

type Logic struct {
	Type    string          `json:"type"`
	Ref     string          `json:"ref,omitempty"`
	Actions []*LogicActions `json:"actions"`
}

type LogicActionDetails

type LogicActionDetails struct {
	To     *LogicJumpDestination `json:"to,omitempty"`
	Target *TargetVariable       `json:"target,omitempty"`
	Value  *VariableValue        `json:"value,omitempty"`
}

type LogicActions

type LogicActions struct {
	Action    string             `json:"action"`
	Details   LogicActionDetails `json:"details"`
	Condition LogicCondition     `json:"condition"`
}

type LogicCondition

type LogicCondition struct {
	Op   string      `json:"op"`
	Vars []*LogicVar `json:"vars"`
}

type LogicEvaluation

type LogicEvaluation struct {
	Op   string            `json:"op"`
	Vars []*TargetVariable `json:"vars"`
}

type LogicJumpDestination

type LogicJumpDestination struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

type LogicVar

type LogicVar struct {
	*LogicCondition
	Type  string      `json:"type,omitempty"`
	Value interface{} `json:"value,omitempty"`
}

type Notifications

type Notifications struct {
	Self       *SelfNotification       `json:"self,omitempty"`
	Respondent *RespondentNotification `json:"respondent,omitempty"`
}

type Outcome

type Outcome struct {
	Variable string           `json:"variable"`
	Choices  []*OutcomeChoice `json:"choices"`
}

type OutcomeChoice

type OutcomeChoice struct {
	ID                string `json:"id,omitempty"`
	Ref               string `json:"ref,omitempty"`
	Title             string `json:"title"`
	CounterVariable   string `json:"counter_variable"`
	ThankYouScreenRef string `json:"thankyou_screen_ref"`
}

type Price

type Price struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

type PropertyLabels

type PropertyLabels struct {
	Left   string `json:"left,omitempty"`
	Center string `json:"center,omitempty"`
	Right  string `json:"right,omitempty"`
}

type RespondentNotification

type RespondentNotification struct {
	Enabled   bool      `json:"enabled"`
	Message   string    `json:"message"`
	Recipient string    `json:"recipient"`
	ReplyTo   *[]string `json:"reply_to,omitempty"`
	Subject   string    `json:"subject"`
}

type Response

type Response struct {
	LandingID   string    `json:"landing_id"`
	Token       string    `json:"token"`
	ResponseID  string    `json:"response_id,omitempty"`
	LandedAt    time.Time `json:"landed_at"`
	SubmittedAt time.Time `json:"submitted_at"`
	Metadata    struct {
		UserAgent string `json:"user_agent"`
		Platform  string `json:"platform"`
		Referer   string `json:"referer"`
		NetworkID string `json:"network_id"`
		Browser   string `json:"browser"`
	} `json:"metadata"`
	Answers []struct {
		Field struct {
			ID   string `json:"id"`
			Type string `json:"type"`
			Ref  string `json:"ref"`
		} `json:"field"`
		Type    string `json:"type"`
		Text    string `json:"text,omitempty"`
		Boolean bool   `json:"boolean,omitempty"`
		Email   string `json:"email,omitempty"`
		Number  int    `json:"number,omitempty"`
		Choices struct {
			Labels []string `json:"labels"`
		} `json:"choices,omitempty"`
		Date   time.Time `json:"date,omitempty"`
		Choice struct {
			Label string `json:"label"`
		} `json:"choice,omitempty"`
	} `json:"answers"`
	Hidden     map[string]string      `json:"hidden,omitempty"`
	Calculated map[string]interface{} `json:"calculated"`
}

type ResponseList

type ResponseList struct {
	TotalItems int        `json:"total_items"`
	PageCount  int        `json:"page_count"`
	Items      []Response `json:"items"`
}

type ResponseListParams

type ResponseListParams struct {
	PageSize            int        `url:"page_size,omitempty"`
	Since               *time.Time `url:"since,omitempty"`
	Until               *time.Time `url:"until,omitempty"`
	After               *time.Time `url:"after,omitempty"`
	Before              *time.Time `url:"before,omitempty"`
	IncludedResponseIDs string     `url:"included_response_ids,omitempty"`
	Completed           *bool      `url:"completed,omitempty"`
	Sort                string     `url:"sort,omitempty"`
	Query               string     `url:"query,omitempty"`
	Fields              string     `url:"fields,omitempty"`
}

type ResponseService

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

func NewResponseService

func NewResponseService(client Client) *ResponseService

func (ResponseService) Delete

func (s ResponseService) Delete(formID string, includedTokens []string) error

func (ResponseService) List

type Self

type Self struct {
	Href string `json:"href"`
}

type SelfNotification

type SelfNotification struct {
	Enabled    bool     `json:"enabled"`
	Message    string   `json:"message"`
	Recipients []string `json:"recipients"`
	ReplyTo    string   `json:"reply_to,omitempty"`
	Subject    string   `json:"subject"`
}

type Settings

type Settings struct {
	Language               string         `json:"language"`
	ProgressBar            string         `json:"progress_bar"`
	Meta                   SettingsMeta   `json:"meta"`
	IsPublic               bool           `json:"is_public"`
	IsTrial                bool           `json:"is_trial"`
	ShowProgressBar        bool           `json:"show_progress_bar"`
	ShowTypeformBranding   bool           `json:"show_typeform_branding"`
	RedirectAfterSubmitURL string         `json:"redirect_after_submit_url,omitempty"`
	FacebookPixel          string         `json:"facebook_pixel,omitempty"`
	GoogleAnalytics        string         `json:"google_analytics,omitempty"`
	GoogleTagManager       string         `json:"google_tag_manager,omitempty"`
	Notifications          *Notifications `json:"Notifications,omitempty"`
}

type SettingsMeta

type SettingsMeta struct {
	AllowIndexing bool   `json:"allow_indexing"`
	Description   string `json:"description,omitempty"`
	Image         *Link  `json:"image,omitempty"`
}

type TargetVariable

type TargetVariable struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

type ThankYouScreen

type ThankYouScreen struct {
	ID         string                   `json:"id,omitempty"`
	Ref        string                   `json:"ref,omitempty"`
	Title      string                   `json:"title"`
	Properties ThankYouScreenProperties `json:"properties"`
	Attachment *Attachment              `json:"attachment,omitempty"`
}

type ThankYouScreenProperties

type ThankYouScreenProperties struct {
	ShowButton  *bool  `json:"show_button,omitempty"`
	ShareIcons  *bool  `json:"share_icons,omitempty"`
	ButtonMode  string `json:"button_mode,omitempty"`
	ButtonText  string `json:"button_text,omitempty"`
	RedirectURL string `json:"redirect_url,omitempty"`
	Description string `json:"description,omitempty"`
}

type Theme

type Theme struct {
	ID                   string      `json:"id,omitempty"`
	Name                 string      `json:"name,omitempty"`
	Visibility           string      `json:"visibility,omitempty"`
	Background           *Background `json:"background,omitempty"`
	Colors               *Colors     `json:"colors,omitempty"`
	Font                 string      `json:"font,omitempty"`
	HasTransparentButton bool        `json:"has_transparent_button,omitempty"`
}

type ThemeList

type ThemeList struct {
	Items      []*Theme `json:"items,omitempty"`
	PageCount  int      `json:"page_count"`
	TotalItems int      `json:"total_items"`
}

type ThemeListParams

type ThemeListParams struct {
	Page     int `url:"page,omitempty"`
	PageSize int `url:"page_size,omitempty"`
}

type ThemeService

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

func NewThemeService

func NewThemeService(client Client) *ThemeService

func (ThemeService) Create

func (s ThemeService) Create(t Theme) (Theme, error)

func (ThemeService) Delete

func (s ThemeService) Delete(themeID string) error

func (ThemeService) List

func (ThemeService) Retrieve

func (s ThemeService) Retrieve(themeID string) (Theme, error)

func (ThemeService) Update

func (s ThemeService) Update(t Theme) (Theme, error)

type VariableValue

type VariableValue struct {
	Type       string           `json:"type"`
	Value      interface{}      `json:"value,omitempty"`
	Evaluation *LogicEvaluation `json:"evaluation,omitempty"`
}

type WelcomeScreen

type WelcomeScreen struct {
	ID         string                  `json:"id,omitempty"`
	Ref        string                  `json:"ref,omitempty"`
	Title      string                  `json:"title"`
	Properties WelcomeScreenProperties `json:"properties"`
	Attachment *Attachment             `json:"attachment,omitempty"`
}

type WelcomeScreenProperties

type WelcomeScreenProperties struct {
	ShowButton  *bool  `json:"show_button,omitempty"`
	ButtonText  string `json:"button_text,omitempty"`
	Description string `json:"description,omitempty"`
}

type Workspace

type Workspace struct {
	ID        string            `json:"id,omitempty"`
	Name      string            `json:"name"`
	AccountID string            `json:"account_id,omitempty"`
	Default   bool              `json:"default,omitempty"`
	Shared    bool              `json:"shared,omitempty"`
	Forms     *Forms            `json:"forms,omitempty"`
	Members   []WorkspaceMember `json:"members,omitempty"`
	Self      *Self             `json:"self,omitempty"`
}

type WorkspaceList

type WorkspaceList struct {
	Items      []*Workspace `json:"items,omitempty"`
	PageCount  int          `json:"page_count"`
	TotalItems int          `json:"total_items"`
}

type WorkspaceMember

type WorkspaceMember struct {
	Email string `json:"email"`
	Name  string `json:"name"`
	Role  string `json:"role"`
}

type WorkspaceService

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

func NewWorkspaceService

func NewWorkspaceService(client Client) *WorkspaceService

func (WorkspaceService) Create

func (s WorkspaceService) Create(w Workspace) (Workspace, error)

func (WorkspaceService) Delete

func (s WorkspaceService) Delete(workspaceID string) error

func (WorkspaceService) List

func (s WorkspaceService) List() (WorkspaceList, error)

func (WorkspaceService) Retrieve

func (s WorkspaceService) Retrieve(workspaceID string) (Workspace, error)

Jump to

Keyboard shortcuts

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