itembase

package module
v0.0.0-...-38ba192 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2015 License: Apache-2.0 Imports: 12 Imported by: 0

README

Go Itembase

Helper library for invoking the Itembase REST API. Supports the following operations:

Based on the great work of cosn, JustinTulloss and ereyes01 on the Firebase REST API.

Usage

GoDoc

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.
  • Dowload the package:
go get github.com/saasbuilders/itembase
Config
import "github.com/saasbuilders/itembase"

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.

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

This section is empty.

Types

type Address

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

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
	//  - `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 implemenation 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 Billing

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

type Brand

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

type Buyer

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

type Buyers

type Buyers struct {
	Buyers               []Buyer `json:"documents"`
	NumDocumentsFound    float64 `json:"num_documents_found"`
	NumDocumentsReturned float64 `json:"num_documents_returned"`
}

type Category

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

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
	Get() (destination interface{}, err error)

	Me() (destination User, 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 string) Client
	CreatedAtTo(value string) Client
	UpdatedAtFrom(value string) Client
	UpdatedAtTo(value string) Client
	Limit(limit uint) Client
	Offset(offset uint) Client

	SaveToken(userId string, token *oauth2.Token) (err error)
	GetCachedToken(userId string) (token *oauth2.Token, err error)
	GiveTokenPermissions(authUrl string) (authcode string, err error)
}

func New

func New(options Config, api Api) Client

func NewClient

func NewClient(root, auth string, api Api) Client

type Config

type Config struct {
	ClientID     string
	ClientSecret string
	Scopes       []string
	TokenHandler ItembaseTokens
	Production   bool
	RedirectURL  string
}

type Contact

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

type ItembaseError

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

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

func (*ItembaseError) Error

func (f *ItembaseError) Error() string

type ItembaseTokens

type ItembaseTokens struct {
	TokenLoader      TokenLoader
	TokenSaver       TokenSaver
	TokenPermissions TokenPermissions
}

type Product

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

type ProductDescription

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

type Products

type Products struct {
	Products             []Product `json:"documents"`
	NumDocumentsFound    float64   `json:"num_documents_found"`
	NumDocumentsReturned float64   `json:"num_documents_returned"`
}

type Profile

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

type Profiles

type Profiles struct {
	Profiles             []Profile `json:"documents"`
	NumDocumentsFound    float64   `json:"num_documents_found"`
	NumDocumentsReturned float64   `json:"num_documents_returned"`
}

type TokenLoader

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

type TokenPermissions

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

type TokenSaver

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

type Transaction

type Transaction struct {
	Billing           Billing   `json:"billing"`
	Buyer             Buyer     `json:"buyer"`
	CreatedAt         string    `json:"created_at"`
	Currency          string    `json:"currency"`
	ID                string    `json:"id"`
	OriginalReference string    `json:"original_reference"`
	Products          []Product `json:"products"`
	Shipping          struct {
		Address Address `json:"address"`
	} `json:"shipping"`
	SourceID string `json:"source_id"`
	Status   struct {
		Global   string `json:"global"`
		Payment  string `json:"payment"`
		Shipping string `json:"shipping"`
	} `json:"status"`
	TotalPrice    float64 `json:"total_price"`
	TotalPriceNet float64 `json:"total_price_net"`
	TotalTax      float64 `json:"total_tax"`
	UpdatedAt     string  `json:"updated_at"`
}

type Transactions

type Transactions struct {
	Transactions         []Transaction `json:"documents"`
	NumDocumentsFound    float64       `json:"num_documents_found"`
	NumDocumentsReturned float64       `json:"num_documents_returned"`
}

type User

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

Jump to

Keyboard shortcuts

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