bc

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: May 20, 2024 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const ContentTypeJSON = "application/json"
View Source
const DataAccessReadOnly = "ReadOnly"
View Source
const NoODATAMetadata = "odata.metadata=none"
View Source
const OrderAscending = "ASC"
View Source
const OrderDescending = "DESC"

Variables

View Source
var AcceptJSONNoMetadata = strings.Join([]string{ContentTypeJSON, NoODATAMetadata}, ";")

This is the "Accept" header value to return JSON without the OData metadata. It's semicolon separated. Included in all requests.

View Source
var (
	ErrorEmptyString = errors.New("empty string")
)

Functions

func BuildBaseURL

func BuildBaseURL(cfg ClientConfig) (*url.URL, error)

dksdlfjdsja BuildBaseURL builds the BaseURL from the ClientConfig. It uses the structure "https://api.businesscentral.dynamics.com/v2.0/{tenantID}/{environment}/api/{APIendpoint}/companies({companyID})"

func BuildRequestURL

func BuildRequestURL(baseURL url.URL, entitySet string, recordID GUID, queryParams QueryParams) url.URL

BuildRequestURL builds a URL to be used in an http.Request. It uses the structure https://api.businesscentral.dynamics.com/v2.0/{tenantID}/{environment}/api/{APIendpoint}/companies({companyID})/{entitySet}({recordID})?{queryParams}

func Decode

func Decode[T Validator](r *http.Response) (T, error)

Decodes the http.Response into either an error or type T. The error can be inspected with errors.As to check if it is a APIError or an error during decoding.

func DecodeNoContent added in v0.8.0

func DecodeNoContent(r *http.Response) error

Decodes the http.Response into an error. The error can be inspected with errors.As to check if it is a APIError or an error during decoding.

func ValidateStruct

func ValidateStruct(s any) error

ValidateStruct uses the validate instance to validate a struct and return an error. It calls the validate.Struct method and does a check for the InvalidValidationError.

Types

type APIError added in v0.8.0

type APIError struct {
	Code          string
	Message       string
	StatusCode    int
	CorrelationID GUID
	Request       *http.Request
}

APIError is a combination of the inner error and the StatusCode returned by the BC server when responding with an error status. It meets the Error interface.

func (APIError) Error added in v0.8.0

func (err APIError) Error() string

type APIListResponse

type APIListResponse[T any] struct {
	Value []T `json:"value" validate:"required,dive"`
}

APIListResponse is the response body of a valid GET request that does not have a RecordID. The Value field has a slice of T.

func (APIListResponse[T]) Validate

func (a APIListResponse[T]) Validate() error

type APIPage

type APIPage[T Validator] struct {
	// contains filtered or unexported fields
}

APIPage represents an API page in Business Central. It has the CRUD methods as well as a List method that returns a list of entities[T]. Set a base filter with SetBaseFilter and an expand string with SetBaseExpand.

func NewAPIPage

func NewAPIPage[T Validator](client *Client, entitySetName string) (*APIPage[T], error)

NewAPIPage creates an instance of an APIPage. It validates that the *Client is not nil and entitySetName is not empty. Call SetBaseExpand or SetBaseFilter on the APIPage to set the baseExpand/baseFilter.

func (*APIPage[T]) AddBaseExpand

func (a *APIPage[T]) AddBaseExpand(expand string)

Adds a new string to the baseExpand slice. This will be added to all request expand expressions.

func (*APIPage[T]) BaseExpand

func (a *APIPage[T]) BaseExpand() []string

Returns the BaseExpand.

func (*APIPage[T]) Delete added in v0.8.0

func (a *APIPage[T]) Delete(ctx context.Context, id GUID) error

Delete makes a DELETE request to the endpoint and returns a string message. It requires a RecordID.

func (*APIPage[T]) Get

func (a *APIPage[T]) Get(ctx context.Context, id GUID, expand []string) (T, error)

Get makes a GET request to the endpoint and retrieves a single record T. Requires the ID and takes an optional slice of expand strings.

func (*APIPage[T]) List

func (a *APIPage[T]) List(ctx context.Context, queryOpts ListPageOptions) ([]T, error)

List makes a GET request to the endpoint and returns []T. It takes optional struct of query options.

func (*APIPage[T]) New added in v0.5.0

func (a *APIPage[T]) New(ctx context.Context, expand []string, body any) (T, error)

New makes a Patch request to the endpoint and returns T. It requires a body.

func (*APIPage[T]) SetBaseExpand

func (a *APIPage[T]) SetBaseExpand(expands []string)

Sets the baseExpand slice. This will be added to all request expand expressions.

func (*APIPage[T]) SetBaseFilter

func (a *APIPage[T]) SetBaseFilter(filter string)

Sets the base filter string. This will be added to all request filters.

func (*APIPage[T]) Update

func (a *APIPage[T]) Update(ctx context.Context, id GUID, expand []string, body any) (T, error)

Update makes a Patch request to the endpoint and returns T. It requires a body and a RecordID.

type APIQuery

type APIQuery[T any] struct {
	// contains filtered or unexported fields
}

func NewAPIQuery

func NewAPIQuery[T any](client *Client, entitySetName string) (*APIQuery[T], error)

func (*APIQuery[T]) List

func (q *APIQuery[T]) List(ctx context.Context, filter string, orderby string, top int) ([]T, error)

func (*APIQuery[T]) SetBaseFilter

func (q *APIQuery[T]) SetBaseFilter(filter string)

type AccessToken

type AccessToken string

AccessToken is used in the Authorization header of requests.

type Auth

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

Auth is used to retrieve an AccessToken. Implements the TokenGetter interface.

func NewAuth

func NewAuth(tenantID GUID, clientID GUID, clientSecret string, logger *slog.Logger) (*Auth, error)

NewAuth validates the AuthParams and creates a new AuthClient.

func (*Auth) GetToken

func (ac *Auth) GetToken(ctx context.Context) (AccessToken, error)

type Client

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

Client is used to send and receive HTTP requests/responses to the API server. There should be one client created per publisher/group/version combination as these can each have their own schemas. Clients can share the authClient if they are using the same scope.

func NewClient

func NewClient(config ClientConfig, authClient TokenGetter, opts ...ClientOptionFunc) (*Client, error)

New client takes the mandatory ClientConfig params, a TokenGetter, and optional configuration using the functional options pattern. Logger and HTTPClient will be set to defaults if not optionally set.

func (*Client) APIEndpoint

func (c *Client) APIEndpoint() string

APIEndpoint returns the API endpoint, either the version for a common endpoint or the <publisher>/<group>/<version> if an extension API.

func (*Client) BaseClient

func (c *Client) BaseClient() *http.Client

BaseClient returns the baseClient *http.Client.

func (*Client) Config

func (c *Client) Config() ClientConfig

Config returns ClientConfig for this instance.

func (*Client) Do

func (c *Client) Do(r *http.Request) (*http.Response, error)

func (*Client) IsCommon

func (c *Client) IsCommon() bool

IsCommon returns true if it is a common service endpoint.

func (*Client) Logger

func (c *Client) Logger() *slog.Logger

BaseClient returns the logger *slog.Logger.

func (*Client) NewRequest

func (c *Client) NewRequest(ctx context.Context, opts RequestOptions) (*http.Request, error)

NewRequest is the base method that creates the http.Request. It has the same return as http.RequestWithContext.

type ClientConfig

type ClientConfig struct {
	// TenantID is the Entra Tenant ID for the organization.
	TenantID GUID
	// CompanyID is the BC company within the environment.
	CompanyID GUID
	// Environment must be a non-empty string.
	Environment string
	// APIEndpoint must be either "v2.0" or the format
	//"<publisher>/<group>/<version>".
	APIEndpoint string
}

The required configuration options for the Client. Meets the Validator interface.

func (ClientConfig) Validate

func (p ClientConfig) Validate() error

Validates that the params are all in correct format.

type ClientOptionFunc

type ClientOptionFunc func(*clientOptions)

ClientOption modifies the ClientOptions struct.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOptionFunc

WithHTTPClient sets an http.Client instead of using the default baseClient.

func WithLogger

func WithLogger(logger *slog.Logger) ClientOptionFunc

WithLogger sets a *slog.Logger instead of the default.

type Date

type Date struct {
	Year  int
	Month time.Month
	Day   int
}

Date represents a Date type in Business Central. It has no time zone associated with so does not represent a unique moment. When converting a time.Time to this Date make sure that it is set with the correct time.Location. It can be marshaled and unmarshaled and satisfies the Stringer interface. Heavily inspired by the civil package: https://github.com/googleapis/google-cloud-go/blob/v0.112.0/civil/civil.go

func DateOf

func DateOf(time time.Time) Date

DateOf transforms a time.Time into a Date using that time.Time's location.

func ParseDate

func ParseDate(s string) (Date, error)

ParseDate transforms a string format 'YYYY-MM-DD' to a Date.

func (Date) IsZero

func (d Date) IsZero() bool

IsZero returns true if the Date is set to the zero value.

func (Date) MarshalJSON

func (d Date) MarshalJSON() ([]byte, error)

MarshalJSON just returns it as a string formatted 'YYYY-MM-DD'.

func (Date) String

func (d Date) String() string

String formats it 'YYYY-MM-DD'

func (Date) TimeUTC added in v0.13.0

func (d Date) TimeUTC() time.Time

Time returns a time.Time representing the Date at UTC time 00:00.

func (*Date) UnmarshalJSON

func (d *Date) UnmarshalJSON(data []byte) error

UnmarshalJSON takes the date string (formatted 'YYYY-MM-DD') and converts it to a Date.

type ErrorResponse

type ErrorResponse struct {
	Error ErrorResponseError `json:"error"`
}

ErrorResponse is the body of the response returned from Business Central when the status is an error status.

type ErrorResponseError

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

The inner error field of the error response from BC.

type GUID

type GUID string

GUID represents a Microsoft GUID and implements the Validator interface.

func (GUID) Validate

func (id GUID) Validate() error

type ListPageOptions

type ListPageOptions struct {
	Filter         string
	Expand         []string
	OrderBy        string
	OrderDirection string
	Skip           int
	Top            int
}

ListPageOptions are the different OData filters and expressions that are sent as query params in the request to an APIPage.

func (ListPageOptions) BuildQueryParams

func (q ListPageOptions) BuildQueryParams(baseFilter string, baseExpand []string) (QueryParams, error)

BuildQueryParams combines the base filter/expand with the provided ListQueryOptions to return QueryParams for the request.

type QueryParams

type QueryParams map[string]string

QueryParams are used to build the http.Request url.

type RequestOptions

type RequestOptions struct {
	Method        string
	EntitySetName string
	RecordID      GUID
	QueryParams   QueryParams
	Body          any
}

MakeRequestOptions are the unique options for the http.Request.

func (RequestOptions) Validate

func (r RequestOptions) Validate() error

type TokenGetter

type TokenGetter interface {
	GetToken(context.Context) (AccessToken, error)
}

TokenGetter represents a client that retrieves an AccessToken.

type URLString

type URLString string

URL represents a URL string and implements the Validator interface

func (URLString) Validate

func (u URLString) Validate() error

type Validator

type Validator interface {
	Validate() error
}

Jump to

Keyboard shortcuts

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