itembase

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

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

Go to latest
Published: Jan 19, 2016 License: Apache-2.0 Imports: 16 Imported by: 0

README

Go Itembase

GoDoc

A Go (golang) REST client library for the Itembase API. Supports all entities from the Itembase API endpoints:

  • Buyers
  • Products
  • Store Profiles
  • Transactions

Installation

  • Setup your GOPATH and workspace. If you are new to Go and you're not sure how to do this, read How to Write Go Code.
  • Download the package:
go get gopkg.in/saasbuilders/itembase.v0

Usage

High-level examples are shown here, see the GoDoc for the complete API.

Config
import "gopkg.in/saasbuilders/itembase.v0"

config := itembase.Config{
	ClientID:     "YOUR CLIENT ID",
	ClientSecret: "YOUR CLIENT SECRET",
	Scopes:       []string{"user.minimal", "connection.transaction", "connection.product", "connection.profile", "connection.buyer"},
	TokenHandler: TokenHandler(),
	RedirectURL:  "http://yourredirecturl.com",
	Production:   false,
}
Instantiating
storeRef := itembase.
	New(config, nil).
	User("13ac2c74-7de3-4436-9a6d-2c94dd2b1fd3")

me, err := storeRef.Me()
if err != nil {
	log.Fatal(err)
}

pretty.Println(me)
Queries
var transactions itembase.Transactions
err = storeRef.Transactions().Select("6ee2e2d9f7baea5132ab79b").GetInto(&transactions)

if err != nil {
	log.Fatal(err)
}
pretty.Println(transactions)
Querying Buyers
pretty.Println(storeRef.Buyers().Select("95d5c9ceeaad98706ce").URL())

var buyers itembase.Buyers
err := storeRef.Buyers().GetInto(&buyers)

if err != nil {
	log.Fatal(err)
}
pretty.Println(buyers)
Querying the Store Profile
pretty.Println(storeRef.Profiles().URL())

var profiles itembase.Profiles
err := storeRef.Products().GetInto(&profiles)

if err != nil {
	log.Fatal(err)
}
pretty.Println(profiles)
Querying Store Products
pretty.Println(storeRef.Products().URL())
pretty.Println(storeRef.Products().Select("ee6f8dc930f5bcb671a0").URL())

var products itembase.Products
err := storeRef.Products().GetInto(&products)

if err != nil {
	log.Fatal(err)
}
pretty.Println(products)

Querying Store Transactions
pretty.Println(storeRef.Transactions().URL())
pretty.Println(storeRef.Transactions().Select("6ee2e2d9f7baea5132ab79b").URL())
pretty.Println(storeRef.Transactions().CreatedAtFrom("2015-04-29T08:53:01.738+0200").Limit(2).Offset(6).URL())

var transactions itembase.Transactions
err := storeRef.Transactions().CreatedAtFrom("2015-05-07T09:53:01").Limit(3).Offset(6).GetInto(&transactions)

if err != nil {
	log.Fatal(err)
}
pretty.Println(transactions)

Query Functions

You can stack the different limitation options when it makes sense like so :

  • Date specific filters - works for Transactions and Products
storeRef.Transactions().CreatedAtFrom("2015-05-07T09:53:01")
storeRef.Transactions().CreatedAtTo("2015-05-07T09:53:01")
storeRef.Transactions().UpdatedAtFrom("2015-05-07T09:53:01")
storeRef.Transactions().UpdatedAtTo("2015-05-07T09:53:01")
  • Limits and pagination. Similar to SQL Limit syntax. Works with Transactions and Products
storeRef.Transactions().Limit(10)
storeRef.Transactions().Limit(10).Offset(10)
  • Selecting specific entries - works with Transactions, Buyers and Products
storeRef.Transactions().Select("6ee2e2d9f7baea5132ab79b")
Token Handlers

You will want to add your own token handlers to save tokens in your own datastore / database. You can define how to retrieve the oauth token for a user, how to save it, and what to do when it expires. Set to nil if you don't want to override the usual functions, which would only make sense for the last one, as the saving and loading should be handled.

func TokenHandler() itembase.ItembaseTokens {
	return itembase.ItembaseTokens{
		GetCachedToken, // How to retrieve a valid oauth token for a user
		SaveToken,      // How to save a valid oauth token for a user
		nil,            // What to do in case of expired tokens
	}
}

func GetCachedToken(userID string) (token *oauth2.Token, err error) {

	// retrieve oauth2.Token from your Database and assign it to &token

	if token == nil {
		err = errors.New("No Refresh Token!")
	}

	return
}

func SaveToken(userID string, token *oauth2.Token) (err error) {

	// save oauth2.Token to your Database for userID

	return
}

func TokenPermissions(authURL string) (authcode string, err error) {
	
	// token expired, offline authURL provided
	// handle the token permission process, and return the new authcode

	return
}

Off you go, now enjoy.

Credits

Originally based on the great work of cosn, JustinTulloss and ereyes01 on the Firebase API client.

Documentation

Overview

Package itembase gives a thin wrapper around the itembase REST API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertTo

func ConvertTo(inputInterface, outputType interface{}) error

Types

type API

type API interface {
	// Call is responsible for performing HTTP transactions such as GET, POST,
	// PUT, PATCH, and DELETE. It is used to communicate with Itembase by all
	// of the Client methods.
	//
	// Arguments are as follows:
	//  - `method`: The http method for this call
	//  - `path`: The full itembase url to call
	//	- `auth`: TODO
	//  - `body`: Data to be marshalled to JSON (it's the responsibility of Call to do the marshalling and unmarshalling)
	//  - `params`: Additional parameters to be passed to itembase
	//  - `dest`: The object to save the unmarshalled response body to.
	//    It's up to this method to unmarshal correctly, the default implementation just uses `json.Unmarshal`
	Call(method, path, auth string, body interface{}, params map[string]string, dest interface{}) error
}

API is the internal interface for interacting with Itembase. The internal implementation of this interface is responsible for all HTTP operations that communicate with Itembase.

Users of this library can implement their own API-conformant types for testing purposes. To use your own test API type, pass it in to the NewClient function.

type Address

type Address struct {
	City    string `json:"city,omitempty"`
	Country string `json:"country,omitempty"`
	Line1   string `json:"line_1,omitempty"`
	Name    string `json:"name,omitempty"`
	Zip     string `json:"zip,omitempty"`
}

An Address represents a mailing address model from the itembase API.

type Billing

type Billing struct {
	Address Address `json:"address,omitempty"`
}

Billing represents a model from the itembase API containing the billing address of a Transaction.

type Brand

type Brand struct {
	Name struct {
		Language string `json:"language,omitempty"`
		Value    string `json:"value,omitempty"`
	} `json:"name,omitempty"`
}

A Brand represents a product brand model from the itembase API.

type Buyer

type Buyer struct {
	Active            bool       `json:"active,omitempty"`
	Contact           Contact    `json:"contact,omitempty"`
	CreatedAt         *time.Time `json:"created_at,omitempty"`
	Currency          string     `json:"currency,omitempty"`
	DateOfBirth       string     `json:"date_of_birth,omitempty"`
	FirstName         string     `json:"first_name,omitempty"`
	ID                BuyerID    `json:"id"`
	Language          string     `json:"language,omitempty"`
	LastName          string     `json:"last_name,omitempty"`
	Locale            string     `json:"locale,omitempty"`
	Note              string     `json:"note,omitempty"`
	OptOut            bool       `json:"opt_out,omitempty"`
	OriginalReference string     `json:"original_reference,omitempty"`
	SourceID          string     `json:"source_id,omitempty"`
	Status            string     `json:"status,omitempty"`
	Type              string     `json:"type,omitempty"`
	UpdatedAt         *time.Time `json:"updated_at,omitempty"`
	URL               string     `json:"url,omitempty"`
}

A Buyer represents a buyer entity from the itembase API.

See http://sandbox.api.itembase.io/swagger-ui/

func (*Buyer) GetEmail

func (buyer *Buyer) GetEmail() string

GetEmail returns an Email for a Profile

func (*Buyer) GetEmails

func (buyer *Buyer) GetEmails() (emails []string)

GetEmails returns all Emails for a Profile

func (*Buyer) GetName

func (buyer *Buyer) GetName() string

GetName returns a string with a combined FirstName and LastName of a Buyer Profile

type BuyerID

type BuyerID string

func (BuyerID) String

func (buyerID BuyerID) String() string

type Buyers

type Buyers struct {
	Buyers []Buyer `json:"documents"`
}

Buyers is a container for pagination of Buyer entities.

func (*Buyers) Add

func (buyers *Buyers) Add(buyer interface{}) error

func (*Buyers) ByShop

func (buyers *Buyers) ByShop(shopID string) (filteredBuyers Buyers)

func (*Buyers) Count

func (buyers *Buyers) Count() int

func (*Buyers) Exists

func (buyers *Buyers) Exists(searchBuyer Buyer) bool

func (*Buyers) MaxCreatedAt

func (buyers *Buyers) MaxCreatedAt() time.Time

Return date of heighest Created At buyer

func (*Buyers) MaxUpdatedAt

func (buyers *Buyers) MaxUpdatedAt() time.Time

Return date of heighest Updated At buyer

type Category

type Category struct {
	CategoryID string `json:"category_id,omitempty"`
	Language   string `json:"language,omitempty"`
	Value      string `json:"value,omitempty"`
}

A Category represents a product category model from the itembase API.

type Client

type Client interface {
	// Returns the absolute URL path for the client
	URL() string

	// Gets the value referenced by the client and unmarshals it into
	// the passed in destination.
	GetInto(destination interface{}) error

	// Paginates through all possible values from client, and unmarshals
	// into the passed in destination
	GetAllInto(destination interface {
		Add(interface{}) error
		Count() int
		MaxCreatedAt() time.Time
		MaxUpdatedAt() time.Time
	}) error

	// Returns how many documents were found
	Found() (count int, err error)

	// Gets values referenced by the client, and returns them as generic interface(!)
	Get() (destination interface{}, err error)

	Me() (destination User, err error)
	Activate() (destination interface{}, err error)

	// Child returns a reference to the child specified by `path`. This does not
	// actually make a request to itembase, but you can then manipulate the reference
	// by calling one of the other methods (such as `GetInto` or `Get`).
	Child(path string) Client

	Transactions() Client
	Products() Client
	Profiles() Client
	Buyers() Client

	Sandbox() Client

	User(path string) Client

	Select(prop string) Client
	CreatedAtFrom(value time.Time) Client
	CreatedAtTo(value time.Time) Client
	UpdatedAtFrom(value time.Time) Client
	UpdatedAtTo(value time.Time) Client
	Limit(limit uint) Client
	Offset(offset uint) Client

	Max(max int) Client

	SaveToken(userID string, token *oauth2.Token) (err error)
	GetCachedToken(userID string) (token *oauth2.Token, err error)
	GiveTokenPermissions(authURL string) (authcode string, err error)

	HandleOAuthCode(authcode string) (*oauth2.Token, error)
	GetUserIDForToken(token *oauth2.Token) (string, error)
}

A Client retrieves data from the itembase API. Use itembase.New to create an instance of the default implementation.

TODO: document each method

func New

func New(options Config, api API) Client

New creates a new instance of the default itembase Client implementation.

The options must be non-nil and must provide all OAuth2 credentials and configuration for an application registered with the itembase API.

TODO: always use the default API impl, NewClient allows dependency injection needed for testing.

func NewClient

func NewClient(root, auth string, options Config, api API) Client

NewClient is an alternative Client constructor intended for testing or advanced usage, where a custom API implementation can be injected.

type Config

type Config struct {
	// ClientID is the OAuth2 application ID for a registered itembase app.
	// See oauth2.Config.
	ClientID string

	// ClientSecret is the application's OAuth2 secret credential.
	// See oauth2.Config.
	ClientSecret string

	// Scopes specify requested OAuth2 permissions, as defined by the itembase
	// API. See oauth2.Config.
	Scopes []string

	// A TokenHandler provides handlers for lifecycle events of OAuth2 tokens.
	TokenHandler ItembaseTokens

	// Production may be set to false to put a Client into sandbox mode.
	Production bool

	// RedirectURL is the URL to redirect users after requesting OAuth2
	// permission grants from itembase. See oauth2.Config.
	RedirectURL string
}

A Config structure is used to configure an itembase Client instance.

type Contact

type Contact struct {
	Addresses []Address `json:"addresses,omitempty"`
	Emails    []struct {
		Value string `json:"value,omitempty"`
	} `json:"emails,omitempty"`
	Phones []interface{} `json:"phones,omitempty"`
}

A Contact represents a container of contact information from itembase API models.

type Error

type Error struct {
	Message string `json:"message"`
	Code    int    `json:"code"`
}

Error is a Go representation of the error message sent back by itembase when a request results in an error.

func (*Error) Error

func (f *Error) Error() string

type Identifier

type Identifier struct {
	ID string `json:"id,omitempty"`
}

type ItembaseResponse

type ItembaseResponse struct {
	Documents            []interface{} `json:"documents"`
	NumDocumentsFound    int           `json:"num_documents_found"`
	NumDocumentsReturned int           `json:"num_documents_returned"`
}

ItembaseResponse is a container for any Itembase response. It returns the resultset, Number of found documents and Number of documents returned

type ItembaseTokens

type ItembaseTokens struct {
	TokenLoader      TokenLoader
	TokenSaver       TokenSaver
	TokenPermissions TokenPermissions
}

ItembaseTokens is a container struct holding handler functions for events in an OAuth2 token's lifecycle.

type Product

type Product struct {
	Active      bool                 `json:"active,omitempty"`
	Brand       Brand                `json:"brand,omitempty"`
	Categories  []Category           `json:"categories,omitempty"`
	Condition   string               `json:"condition,omitempty"`
	CreatedAt   *time.Time           `json:"created_at,omitempty"`
	Currency    string               `json:"currency,omitempty"`
	Description []ProductDescription `json:"description,omitempty"`
	ID          ProductID            `json:"id"`
	Identifier  Identifier           `json:"identifier,omitempty"`
	Name        []struct {
		Language string `json:"language,omitempty"`
		Value    string `json:"value,omitempty"`
	} `json:"name,omitempty"`
	OriginalReference string `json:"original_reference,omitempty"`
	PictureUrls       []struct {
		URLOriginal string `json:"url_original,omitempty"`
	} `json:"picture_urls,omitempty"`
	PricePerUnit float64 `json:"price_per_unit,omitempty"`
	Shipping     []struct {
		Price           float64 `json:"price,omitempty"`
		ShippingService string  `json:"shipping_service,omitempty"`
	} `json:"shipping,omitempty"`
	SourceID         string           `json:"source_id,omitempty"`
	StockInformation StockInformation `json:"stock_information,omitempty"`
	Tax              float64          `json:"tax,omitempty"`
	TaxRate          float64          `json:"tax_rate,omitempty"`
	UpdatedAt        *time.Time       `json:"updated_at,omitempty"`
	URL              string           `json:"url,omitempty"`
	Variants         []interface{}    `json:"variants,omitempty"`
}

A Product represents a product entity from the itembase API.

See http://sandbox.api.itembase.io/swagger-ui/

func (*Product) GetDefaultName

func (product *Product) GetDefaultName() (name string, ok bool)

Returns any name for Product

func (*Product) GetName

func (product *Product) GetName(preferredLanguage string) (name string, ok bool)

Returns name for specified preferred language if present

func (*Product) InStock

func (product *Product) InStock() bool

type ProductDescription

type ProductDescription struct {
	Language string `json:"language,omitempty"`
	Value    string `json:"value,omitempty"`
}

A ProductDescription represents a product description model from the itembase API, which may be in a specified language.

type ProductID

type ProductID string

func (ProductID) String

func (productID ProductID) String() string

type Products

type Products struct {
	Products []Product `json:"documents"`
}

Products is a container for pagination of Product entities.

func (*Products) Add

func (products *Products) Add(product interface{}) error

func (*Products) ByShop

func (products *Products) ByShop(shopID string) (filteredProducts Products)

Get Products based on shopID

func (*Products) Count

func (products *Products) Count() int

func (*Products) Exists

func (products *Products) Exists(searchProduct Product) bool

func (*Products) InStock

func (products *Products) InStock() (filteredProducts Products)

func (*Products) MaxCreatedAt

func (products *Products) MaxCreatedAt() time.Time

Return date of heighest Created At product

func (*Products) MaxUpdatedAt

func (products *Products) MaxUpdatedAt() time.Time

Return date of heighest Updated At product

type Profile

type Profile struct {
	Active    bool   `json:"active,omitempty"`
	AvatarURL string `json:"avatar_url,omitempty"`
	Contact   struct {
		Contact []Contact `json:"contact,omitempty"`
	} `json:"contact,omitempty"`
	CreatedAt         *time.Time `json:"created_at,omitempty"`
	Currency          string     `json:"currency,omitempty"`
	DisplayName       string     `json:"display_name,omitempty"`
	ID                ProfileID  `json:"id"`
	Language          string     `json:"language,omitempty"`
	Locale            string     `json:"locale,omitempty"`
	OriginalReference string     `json:"original_reference,omitempty"`
	PlatformID        string     `json:"platform_id,omitempty"`
	PlatformName      string     `json:"platform_name,omitempty"`
	SourceID          string     `json:"source_id,omitempty"`
	Status            string     `json:"status,omitempty"`
	Type              string     `json:"type,omitempty"`
	UpdatedAt         *time.Time `json:"updated_at,omitempty"`
	URL               string     `json:"url,omitempty"`
}

A Profile represents a user profile entity from the itembase API.

See http://sandbox.api.itembase.io/swagger-ui/

type ProfileID

type ProfileID string

func (ProfileID) String

func (profileID ProfileID) String() string

type Profiles

type Profiles struct {
	Profiles []Profile `json:"documents"`
}

Profiles is a container for pagination of Profile entities.

func (*Profiles) Add

func (profiles *Profiles) Add(profile interface{}) error

func (*Profiles) Count

func (profiles *Profiles) Count() int

func (*Profiles) Exists

func (profiles *Profiles) Exists(searchProfile Profile) bool

func (*Profiles) MaxCreatedAt

func (profiles *Profiles) MaxCreatedAt() time.Time

Return date of heighest Created At profile

func (*Profiles) MaxUpdatedAt

func (profiles *Profiles) MaxUpdatedAt() time.Time

Return date of heighest Updated At profile

type Shipping

type Shipping struct {
	Address Address `json:"address,omitempty"`
}

type Status

type Status struct {
	Global   string `json:"global,omitempty"`
	Payment  string `json:"payment,omitempty"`
	Shipping string `json:"shipping,omitempty"`
}

Status describes a transactions' status

type StockInformation

type StockInformation struct {
	InStock        bool    `json:"in_stock,omitempty"`
	InventoryLevel float64 `json:"inventory_level,omitempty"`
	InventoryUnit  string  `json:"inventory_unit,omitempty"`
}

type TokenLoader

type TokenLoader func(userID string) (token *oauth2.Token, err error)

A TokenLoader is called at points during OAuth2 authorization flow when an application might wish to retrieve a persisted token from a data store.

type TokenPermissions

type TokenPermissions func(authURL string) (authcode string, err error)

A TokenPermissions handler is called at points during OAuth2 authorization flow when a grantor might have granted new permissions for an authorization, such as new scopes.

type TokenSaver

type TokenSaver func(userID string, token *oauth2.Token) (err error)

A TokenSaver is called at points during OAuth2 authorization flow when an application might wish to persist the given token to a data store or cache.

type Transaction

type Transaction struct {
	Billing           Billing       `json:"billing,omitempty"`
	Buyer             Buyer         `json:"buyer,omitempty"`
	CreatedAt         *time.Time    `json:"created_at,omitempty"`
	Currency          string        `json:"currency,omitempty"`
	ID                TransactionID `json:"id"`
	OriginalReference string        `json:"original_reference,omitempty"`
	Products          []Product     `json:"products,omitempty"`
	Shipping          Shipping      `json:"shipping,omitempty"`
	SourceID          string        `json:"source_id,omitempty"`
	Status            Status        `json:"status,omitempty"`
	TotalPrice        float64       `json:"total_price,omitempty"`
	TotalPriceNet     float64       `json:"total_price_net,omitempty"`
	TotalTax          float64       `json:"total_tax,omitempty"`
	UpdatedAt         *time.Time    `json:"updated_at,omitempty"`
}

A Transaction represents a transaction entity from the itembase API.

See http://sandbox.api.itembase.io/swagger-ui/

func (*Transaction) Completed

func (t *Transaction) Completed() bool

type TransactionID

type TransactionID string

func (TransactionID) String

func (transactionID TransactionID) String() string

type Transactions

type Transactions struct {
	Transactions []Transaction `json:"documents"`
}

Transactions is a container for pagination of Transaction entities.

func (*Transactions) Add

func (transactions *Transactions) Add(transaction interface{}) error

func (*Transactions) Completed

func (transactions *Transactions) Completed() (filteredTransactions Transactions)

Return only completed transactions

func (*Transactions) Count

func (transactions *Transactions) Count() int

func (*Transactions) Exists

func (transactions *Transactions) Exists(searchTransaction Transaction) bool

func (*Transactions) MaxCreatedAt

func (transactions *Transactions) MaxCreatedAt() time.Time

Return date of heighest Created At transaction

func (*Transactions) MaxUpdatedAt

func (transactions *Transactions) MaxUpdatedAt() time.Time

Return date of heighest Updated At transaction

type User

type User struct {
	UUID              string `json:"uuid"`
	Username          string `json:"username,omitempty"`
	FirstName         string `json:"first_name,omitempty"`
	LastName          string `json:"last_name,omitempty"`
	MiddleName        string `json:"middle_name,omitempty"`
	NameFormat        string `json:"name_format,omitempty"`
	Locale            string `json:"locale,omitempty"`
	Email             string `json:"email,omitempty"`
	PreferredCurrency string `json:"preferred_currency,omitempty"`
}

A User represents a user entity from the itembase API, such as returned from the "me" endpoint.

Jump to

Keyboard shortcuts

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