skalinsdk

package module
v1.8.2 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2024 License: MIT Imports: 15 Imported by: 0

README

Skalin SDK (golang)

How to use it ?

  package main

  import (
    "github.com/karnott/skalin-sdk"
  )

  skalinApi, err := skalinsdk.New("GetSkalinAppClientID", "GetSkalinClientApiID", "GetSkalinClientApiSecret")
  if err != nil {
    panic(err)
  }
  customerId := "1"
  contact := Contact{
    RefId:     "2",
    Customer:  &customerId,
    LastName:  "Ceci est un test de l'API (nom de famille)",
    FirstName: "Ceci est un test de l'API (prénom)",
    Email:     "contact+testapi@karnott.fr",
    Phone:     "0123456789",
    Tags:      []string{"tag1", "tag2", "tag3"},
    CustomAttributes: CustomAttributes{
      "customAttributeId": "Ceci est un test de l'API (attribut personnalisé 2)",
    },
  }
  contactSaved, err := skalinApi.SaveContact(contact)
  if err != nil {
    panic(err)
  }
}

About the test

Because an API SDK need to call real URLs, we add mock to simulate API response. But to test the SDK calling the API, 8 ENV var can be set:

TEST_SKALIN_APP_CLIENT_ID=""
TEST_SKALIN_CLIENT_API_ID=""
TEST_SKALIN_CLIENT_API_SECRET=""
TEST_SKALIN_CONTACT_CUSTOM_ATTRIBUTE_ID=""
TEST_SKALIN_CUSTOMER_CUSTOM_ATTRIBUTE_ID=""
TEST_SKALIN_EXISTING_CUSTOMER_REF_ID=""
TEST_SKALIN_EXISTING_CUSTOMER_ID=""
TEST_SKALIN_EXISTING_CONTACT_ID=""

If these 8 env var are defined, the GET, POST and PATCH APIs will be test with data from Skalin API

Env var

LOG_FORMAT=json # define the skalin sdk log format
LOG_LEVEL=info # define the skalin sdk log level

~ ~

Documentation

Index

Constants

View Source
const (
	SAVE_AGREEMENT_PATH            = "/agreements"
	UPDATE_AGREEMENT_PATH          = "/agreements/%v"
	CREATE_CUSTOMER_AGREEMENT_PATH = "/customers/%v/agreements"
)
View Source
const (
	SKALIN_API_URL  = "https://api.skalin.io/v1"
	SKALIN_AUTH_URL = "https://auth.skalin.io/oauth/token"
	SKALIN_HIT_URL  = "https://collect.skalin.io/hit"
)
View Source
const (
	SAVE_CONTACT_PATH            = "/contacts"
	UPDATE_CONTACT_PATH          = "/contacts/%v"
	CREATE_CUSTOMER_CONTACT_PATH = "/customers/%v/contacts"
)
View Source
const (
	GET_TAGS      = "/tags"
	GET_TAG_BY_ID = "/tags/%v"
)
View Source
const (
	SAVE_CUSTOMER_PATH = "/customers"
)

Variables

View Source
var (
	ErrUndefined     = errors.New("undefined error")
	ErrAuthorization = errors.New("No authorization token was found")
)
View Source
var Log = NewLogger()

Functions

func BuildUrl

func BuildUrl(path string) string

func GetAPIUrl

func GetAPIUrl() string

func NewTracker added in v1.4.0

func NewTracker(clientId string) (skalinTracker, error)

Types

type API

type API interface {
	PutData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)
	PostData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)
	PatchData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)
	GetData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)
	DeleteData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)

	WithToken(token string) API
	GetLogger() *CustomLog
	GetClientID() *string
	SetLogger(logrus.FieldLogger)
	// contains filtered or unexported methods
}

type Agreement

type Agreement struct {
	Id               string      `json:"id,omitempty"`
	CustomerId       *string     `json:"customerId,omitempty"` // correspond to the customer Id
	Customer         *string     `json:"customer,omitempty"`   // correspond to the customer refId
	RefId            string      `json:"refId,omitempty"`
	StartDate        *SkalinDate `json:"startDate,omitempty"`   // need to be at format `YYYY-MM-DD`
	EndDate          *SkalinDate `json:"endDate,omitempty"`     // need to be at format `YYYY-MM-DD`
	RenewalDate      *SkalinDate `json:"renewalDate,omitempty"` // need to be at format `YYYY-MM-DD`
	AutoRenew        bool        `json:"autoRenew,omitempty"`
	Engagement       *int        `json:"engagement,omitempty"` // need pointer because engagement value can be 0
	EngagementPeriod string      `json:"engagementPeriod,omitempty"`
	Notice           *int        `json:"notice,omitempty"` // need pointer because engagement value can be 0
	NoticePeriod     string      `json:"noticePeriod,omitempty"`
	Plan             string      `json:"plan,omitempty"`
	Type             string      `json:"type,omitempty"`
	Mrr              *int        `json:"mrr,omitempty"`
	Fee              *int        `json:"fee,omitempty"`
}

type Contact

type Contact struct {
	Id               string           `json:"id,omitempty"`
	CustomerId       *string          `json:"customerId,omitempty"` // correspond to the customer Id
	Customer         *string          `json:"customer,omitempty"`   // correspond to the customer refId
	RefId            string           `json:"refId,omitempty"`
	Email            string           `json:"email,omitempty"`
	FirstName        string           `json:"firstName,omitempty"`
	LastName         string           `json:"lastName,omitempty"`
	Phone            string           `json:"phone,omitempty"`
	Tags             []string         `json:"tags,omitempty"`
	LastActivityTs   *time.Time       `json:"lastActivityTs,omitempty"`
	CustomAttributes CustomAttributes `json:"-"`
}

func (Contact) MarshalJSON

func (c Contact) MarshalJSON() ([]byte, error)

need custom MarshalJSON to merge custom attributes with contact see the doc of skalin for now, no need to create a custom UnmarshalJson because skalin API does not return custom attributes

type CustomAttributes

type CustomAttributes map[string]interface{}

type CustomLog

type CustomLog struct {
	logrus.FieldLogger
}

func NewLogger

func NewLogger() *CustomLog

func (*CustomLog) AddSkalinApplicationField

func (logger *CustomLog) AddSkalinApplicationField() *logrus.Entry

func (*CustomLog) Errorf

func (logger *CustomLog) Errorf(format string, args ...interface{})

func (*CustomLog) Fatalf

func (logger *CustomLog) Fatalf(format string, args ...interface{})

func (*CustomLog) Infof

func (logger *CustomLog) Infof(format string, args ...interface{})

func (*CustomLog) Panicf

func (logger *CustomLog) Panicf(format string, args ...interface{})

func (*CustomLog) Printf

func (logger *CustomLog) Printf(format string, args ...interface{})

func (*CustomLog) Warnf

func (logger *CustomLog) Warnf(format string, args ...interface{})

func (*CustomLog) Warningf

func (logger *CustomLog) Warningf(format string, args ...interface{})

type Customer

type Customer struct {
	Id               string           `json:"id,omitempty"`
	RefId            string           `json:"refId,omitempty"`
	Name             string           `json:"name,omitempty"`
	Stage            string           `json:"stage,omitempty"`
	Tags             []string         `json:"tags,omitempty"`
	LastActivityTs   *time.Time       `json:"lastActivityTs,omitempty"`
	CustomAttributes CustomAttributes `json:"-"`
}

func (Customer) MarshalJSON

func (c Customer) MarshalJSON() ([]byte, error)

need custom MarshalJSON to merge custom attributes with contact see the doc of skalin for now, no need to create a custom UnmarshalJson because skalin API does not return custom attributes

type CustomerResponse

type CustomerResponse struct {
	Status string   `json:"status"`
	Data   Customer `json:"data"`
}

type EntitiesGeneric added in v1.3.0

type EntitiesGeneric interface {
	Customer | Contact | Agreement | Tag
}

type EntitySlice added in v1.3.0

type EntitySlice[T EntitiesGeneric] interface {
	~[]T // permit to define a core type to use `make` and `append` on generic (https://go.dev/ref/spec#Core_types)
}

type GenericResponse

type GenericResponse[T EntitySlice[V] | EntitiesGeneric, V EntitiesGeneric, U ResponseMetadata] struct {
	Status   string `json:"status"`
	Data     T      `json:"data"`
	Metadata U      `json:"metadata,omitempty"`
}

type GetParams

type GetParams struct {
	Page    *int
	Size    *int
	Sort    *string
	Filters map[string]interface{}
}

type HitAction added in v1.4.0

type HitAction string
const HitActionEvent HitAction = "ev"
const HitActionUserIdendity HitAction = "ui"

type HitEvent added in v1.4.0

type HitEvent struct {
	Name      string `json:"name" validate:"required"`
	EventName string `json:"event_name" validate:"required"`
}

type HitIdentity added in v1.4.0

type HitIdentity struct {
	ID    *string `json:"id,omitempty" validate:"required_without=Email"`
	Email *string `json:"email,omitempty" validate:"required_without=ID,omitempty,email"`
}

type HitTrack added in v1.4.0

type HitTrack struct {
	Action        HitAction   `validate:"required"`
	VisitorID     string      `validate:"required,len=16"`
	VisitID       string      `validate:"required,len=16"`
	Identity      HitIdentity `validate:"required"`
	Event         *HitEvent   `validate:"required_if=Action ev"` // mandatory if action is event
	EventID       *string     `validate:"omitempty,len=16"`
	CustomerID    *string
	Ts            *time.Time
	URL           *string
	CIP           *string // client ip
	CustomHeaders map[string][]string
}

type MockAPI

type MockAPI struct {
	mock.Mock
}

func (*MockAPI) DeleteData added in v1.8.0

func (m *MockAPI) DeleteData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)

func (*MockAPI) GetClientID added in v1.4.0

func (m *MockAPI) GetClientID() *string

func (*MockAPI) GetData

func (m *MockAPI) GetData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)

func (*MockAPI) GetLogger

func (m *MockAPI) GetLogger() *CustomLog

func (*MockAPI) PatchData

func (m *MockAPI) PatchData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)

func (*MockAPI) PostData

func (m *MockAPI) PostData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)

func (*MockAPI) PutData

func (m *MockAPI) PutData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)

func (*MockAPI) SetLogger

func (m *MockAPI) SetLogger(l logrus.FieldLogger)

func (*MockAPI) WithToken

func (m *MockAPI) WithToken(_ string) API

type PaginationMetadata added in v1.3.0

type PaginationMetadata struct {
	Pagination struct {
		Size        int  `json:"size"`
		Page        int  `json:"page"`
		Total       int  `json:"total"`
		HasNextPage bool `json:"hasNextPage"`
	} `json:"pagination"`
}

type ResponseMetadata added in v1.3.0

type ResponseMetadata interface {
	PaginationMetadata
}

type Skalin

type Skalin interface {
	GetContacts(*GetParams) ([]Contact, error)
	SaveContact(Contact) (*Contact, error)
	UpdateContact(Contact) (*Contact, error)
	CreateContactForCustomer(Contact, string) (*Contact, error)
	DeleteContact(Contact) error

	GetCustomers(*GetParams) ([]Customer, error)
	SaveCustomer(Customer) (*Customer, error)

	GetAgreements(*GetParams) ([]Agreement, error)
	SaveAgreement(Agreement) (*Agreement, error)
	UpdateAgreement(Agreement) (*Agreement, error)
	CreateAgreementForCustomer(Agreement, string) (*Agreement, error)
	DeleteAgreement(Agreement) error

	GetTags(*GetParams) ([]Tag, error)
	GetTagByID(id string) (*Tag, error)

	SetLogger(logger logrus.FieldLogger)
}

func New

func New(clientId, clientApiId, clientApiSecret string) (Skalin, error)

type SkalinAPI

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

func (SkalinAPI) DeleteData added in v1.8.0

func (a SkalinAPI) DeleteData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)

func (*SkalinAPI) GetClientID added in v1.4.0

func (a *SkalinAPI) GetClientID() *string

func (SkalinAPI) GetData

func (a SkalinAPI) GetData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)

func (*SkalinAPI) GetLogger

func (a *SkalinAPI) GetLogger() *CustomLog

func (SkalinAPI) PatchData

func (a SkalinAPI) PatchData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)

func (SkalinAPI) PostData

func (a SkalinAPI) PostData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)

func (SkalinAPI) PutData

func (a SkalinAPI) PutData(url, contentType string, extraHeaders map[string][]string, body []byte, queryParams *url.Values, expectedStatusCode int) (*http.Response, []byte, error)

func (*SkalinAPI) SetLogger

func (a *SkalinAPI) SetLogger(logger logrus.FieldLogger)

func (*SkalinAPI) WithClientID

func (a *SkalinAPI) WithClientID(clientID string) API

func (*SkalinAPI) WithToken

func (a *SkalinAPI) WithToken(token string) API

type SkalinDate

type SkalinDate time.Time

need SkalinDate to unmarshal date from skalin API because format is "YYYY-MM-DD"

func (SkalinDate) MarshalJSON

func (s SkalinDate) MarshalJSON() ([]byte, error)

func (*SkalinDate) UnmarshalJSON

func (s *SkalinDate) UnmarshalJSON(b []byte) error

type SkalinResponseError

type SkalinResponseError struct {
	Status  string `json:"status,omitempty"`
	Message string `json:"message,omitempty"`
	Code    int    `json:"code,omitempty"`
}

type SkalinTracking added in v1.4.0

type SkalinTracking interface {
	Hit(HitTrack) error
}

type Tag added in v1.7.0

type Tag struct {
	Id     string `json:"id"`
	Name   string `json:"name"`
	Type   string `json:"type"`
	Entity string `json:"entity"`
	Color  string `json:"color"`
}

Jump to

Keyboard shortcuts

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