utils

package
v0.4.6 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2018 License: AGPL-3.0 Imports: 19 Imported by: 43

Documentation

Index

Constants

View Source
const (
	NIL = iota
	STRING
	DECIMAL
	TIME
	LOCATION
	BOOLEAN
	ERROR
	STRING_SLICE
	DECIMAL_SLICE
	TIME_SLICE
	BOOL_SLICE
	MAP
)
View Source
const (
	DateFormat_yyyy_MM_dd DateFormat = "yyyy-MM-dd"
	DateFormat_MM_dd_yyyy DateFormat = "MM-dd-yyyy"
	DateFormat_dd_MM_yyyy DateFormat = "dd-MM-yyyy"

	TimeFormat_HH_mm       TimeFormat = "hh:mm"
	TimeFormat_hh_mm_tt    TimeFormat = "hh:mm tt"
	TimeFormat_HH_mm_ss    TimeFormat = "HH:mm:ss"
	TimeFormat_hh_mm_ss_tt TimeFormat = "hh:mm:ss tt"
)

Variables

View Source
var EmptyJSONFragment = JSONFragment{}

EmptyJSONFragment is a fragment which has no values

View Source
var NilLanguage = Language("")

NilLanguage represents our nil, or unknown language

View Source
var Validator = validator.New()

Validator is our system validator, it can be shared across threads

View Source
var ZeroTime = time.Time{}

ZeroTime is our uninitialized time value

Functions

func Compare

func Compare(env Environment, arg1 interface{}, arg2 interface{}) (int, error)

Compare returns the difference between the two passed interfaces which must be of the same type

func DateFromString

func DateFromString(env Environment, str string) (time.Time, error)

DateFromString returns a date constructed from the passed in string, or an error if we are unable to extract one

func DateToISO

func DateToISO(date time.Time) string

DateToISO converts the passed in time.Time to a string in ISO8601 format

func DateToString

func DateToString(env Environment, date time.Time) string

DateToString converts the passed in time element to the right format based on the environment settings

func DateToUTCRange added in v0.4.0

func DateToUTCRange(d time.Time, tz *time.Location) (time.Time, time.Time)

func DaysBetween

func DaysBetween(date1 time.Time, date2 time.Time) int

DaysBetween returns the number of calendar days (an int) between the two dates. Note that if these are in different timezones then the local calendar day is used for each and the difference is calculated from that.

func IsMap

func IsMap(v interface{}) bool

func IsNil added in v0.4.0

func IsNil(v interface{}) bool

func IsSlice

func IsSlice(v interface{}) bool

IsSlice returns whether the passed in interface is a slice

func LookupIndex

func LookupIndex(v interface{}, idx int) (interface{}, error)

LookupIndex tries to look up the interface at the passed in index for the passed in slice

func LookupKey

func LookupKey(v interface{}, key string) (value interface{}, err error)

LookupKey tries to look up the interface at the passed in key for the passed in map

func MapLength

func MapLength(v interface{}) (int, error)

MapLength returns the length of the passed in map, it returns an error if the argument is not a map

func MonthsBetween

func MonthsBetween(date1 time.Time, date2 time.Time) int

MonthsBetween returns the number of calendar months (an int) between the two dates. Note that if these are in different timezones then the local calendar day is used for each and the difference is calculated from that.

func ReadEnvironment added in v0.4.0

func ReadEnvironment(data json.RawMessage) (*environment, error)

ReadEnvironment reads an environment from the given JSON

func ResolveVariable

func ResolveVariable(env Environment, variable interface{}, key string) interface{}

ResolveVariable will resolve the passed in string variable given in dot notation and return the value as defined by the VariableResolver passed in.

Example syntaxes:

foo.bar.0  - 0th element of bar slice within foo, could also be "0" key in bar map within foo
foo.bar[0] - same as above

func SliceLength

func SliceLength(v interface{}) (int, error)

SliceLength returns the length of the passed in slice, it returns an error if the argument is not a slice

func Snakify

func Snakify(text string) string

Snakify turns the passed in string into a context reference. We replace all whitespace characters with _ and replace any duplicate underscores

func ToBool

func ToBool(env Environment, test interface{}) (bool, error)

ToBool tests whether the passed in item should be considered True false, 0, "" and nil are false, everything else is true

func ToDate

func ToDate(env Environment, val interface{}) (time.Time, error)

ToDate tries to convert the passed in interface to a time.Time returning an error if that isn't possible

func ToDecimal

func ToDecimal(env Environment, val interface{}) (decimal.Decimal, error)

ToDecimal tries to convert the passed in interface{} to a Decimal value, returning an error if that isn't possible

func ToGoDateFormat

func ToGoDateFormat(format string) (string, error)

ToGoDateFormat converts the passed in format to a GoLang format string.

Format strings we support:

d - day of month, 1-31 dd - day of month, zero padded 0-31 fff - thousandths of a second h - hour of the day 1-12 hh - hour of the day 01-12 H - hour of the day 1-23 HH - hour of the day 01-23 K - hour and minute offset from UTC, or Z fo UTC m - minute 0-59 mm - minute 00-59 M - month 1-12 MM - month 01-12 s - second 0-59 ss - second 00-59 TT - AM or PM tt - am or pm yy - last two digits of year 0-99 yyyy - four digits of your 0000-9999 zzz - hour and minute offset from UTC ignored chars: ' ', ':', ',', 'T', 'Z', '-', '_', '/'

func ToInt

func ToInt(env Environment, val interface{}) (int, error)

ToInt tries to convert the passed in interface{} to an integer value, returning an error if that isn't possible

func ToString

func ToString(env Environment, val interface{}) (string, error)

ToString tries to turn the passed in interface to a string

func ToStringArray

func ToStringArray(env Environment, v interface{}) ([]string, error)

ToStringArray tries to turn the passed in interface (which must be an underlying slice) to a string array

func TokenizeString

func TokenizeString(str string) []string

TokenizeString returns the words in the passed in string, split by non word characters including emojis

func UnmarshalAndValidate added in v0.4.0

func UnmarshalAndValidate(data []byte, obj interface{}, objName string) error

Convenience function to unmarshal an object and validate it

func UnmarshalArray added in v0.4.0

func UnmarshalArray(data json.RawMessage) ([]json.RawMessage, error)

func Validate added in v0.4.0

func Validate(obj interface{}) error

Validate will run validation on the given object and return a set of field specific errors in the format: field <fieldname> <tag specific message>

For example: "field 'flows' is required"

func ValidateAs added in v0.4.0

func ValidateAs(obj interface{}, objName string) error

ValidateAs will run validation on the given object and return a set of field specific errors in the format: field <fieldname> [on <objName>] <tag specific message>

For example: "field 'flows' on 'assets' is required"

Types

type DateFormat

type DateFormat string

func (DateFormat) String

func (df DateFormat) String() string

type Environment

type Environment interface {
	DateFormat() DateFormat
	SetDateFormat(DateFormat)

	TimeFormat() TimeFormat
	SetTimeFormat(TimeFormat)

	Timezone() *time.Location
	SetTimezone(*time.Location)

	Languages() LanguageList
	Locations() (*LocationHierarchy, error)
}

Environment defines the Environment that the Excellent function is running in, this includes the timezone the user is in as well as the preferred date and time formats.

func NewDefaultEnvironment

func NewDefaultEnvironment() Environment

NewDefaultEnvironment creates a new Environment with our usual defaults in the UTC timezone

func NewEnvironment

func NewEnvironment(dateFormat DateFormat, timeFormat TimeFormat, timezone *time.Location, languages LanguageList) Environment

NewEnvironment creates a new Environment with the passed in date and time formats and timezone

type JSONFragment

type JSONFragment []byte

JSONFragment is a thin wrapper around a byte array that takes care of allow key lookups into the json in that byte array

func ToJSON

func ToJSON(env Environment, val interface{}) (JSONFragment, error)

ToJSON tries to turn the passed in interface to a JSON fragment

func (JSONFragment) Default

func (j JSONFragment) Default() interface{}

Default returns the default value for this JSON, which is the JSON itself

func (JSONFragment) MarshalJSON

func (j JSONFragment) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON representation of our fragment, which is just our internal byte array

func (JSONFragment) Resolve

func (j JSONFragment) Resolve(key string) interface{}

Resolve resolves the passed in key, which is expected to be either an integer in the case that our JSON is an array or a key name if it is a map

func (JSONFragment) String

func (j JSONFragment) String() string

String returns the string representation of this JSON, which is just the JSON itself

func (*JSONFragment) UnmarshalJSON

func (j *JSONFragment) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a new JSONFragment from the passed in byte stream. We validate it looks like valid JSON then set our internal byte structure

type Language

type Language string

Language is our internal representation of a language

func ParseLanguage

func ParseLanguage(lang string) (Language, error)

ParseLanguage returns a new Language for the passed in language string, or an error if not found

type LanguageList added in v0.4.0

type LanguageList []Language

func (LanguageList) RemoveDuplicates added in v0.4.0

func (ll LanguageList) RemoveDuplicates() LanguageList

type Location added in v0.4.0

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

Location represents a single Location

func FindLocations added in v0.4.0

func FindLocations(env Environment, name string, level LocationLevel, parent *Location) ([]*Location, error)

FindLocations returns locations with the matching name (case-insensitive), level and parent (optional)

func FindLocationsFuzzy added in v0.4.0

func FindLocationsFuzzy(env Environment, text string, level LocationLevel, parent *Location) ([]*Location, error)

FindLocationsFuzzy returns matching locations like FindLocations but attempts the following strategies to find locations:

  1. Exact match
  2. Match with punctuation removed
  3. Split input into words and try to match each word
  4. Try to match pairs of words

func NewLocation added in v0.4.0

func NewLocation(id LocationID, level LocationLevel, name string) *Location

NewLocation creates a new location object

func (*Location) Aliases added in v0.4.0

func (b *Location) Aliases() []string

func (*Location) Children added in v0.4.0

func (b *Location) Children() []*Location

func (*Location) ID added in v0.4.0

func (b *Location) ID() LocationID

func (*Location) Level added in v0.4.0

func (b *Location) Level() LocationLevel

func (*Location) Name added in v0.4.0

func (b *Location) Name() string

func (*Location) Parent added in v0.4.0

func (b *Location) Parent() *Location

type LocationHierarchy added in v0.4.0

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

LocationHierarchy is a hierarical tree of locations

func NewLocationHierarchy added in v0.4.0

func NewLocationHierarchy(root *Location, numLevels int) *LocationHierarchy

NewLocationHierarchy cretes a new location hierarchy

func ReadLocationHierarchy added in v0.4.0

func ReadLocationHierarchy(data json.RawMessage) (*LocationHierarchy, error)

ReadLocationHierarchy reads a location hierarchy from the given JSON

func (*LocationHierarchy) FindByID added in v0.4.0

func (s *LocationHierarchy) FindByID(id LocationID, level LocationLevel) *Location

FindByID looks for a location in the hierarchy with the given level and ID

func (*LocationHierarchy) FindByName added in v0.4.0

func (s *LocationHierarchy) FindByName(name string, level LocationLevel, parent *Location) []*Location

FindByName looks for all locations in the hierarchy with the given level and name or alias

type LocationID added in v0.4.0

type LocationID string

LocationID is the unique identifier for each location, e.g. an OSM ID

type LocationLevel added in v0.4.0

type LocationLevel int

LocationLevel is a numeric level, e.g. 0 = country, 1 = state

type RequestResponse

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

RequestResponse represents both the outgoing request and response for a particular URL/method/body

func MakeHTTPRequest

func MakeHTTPRequest(req *http.Request) (*RequestResponse, error)

MakeHTTPRequest fires the passed in http request, returning any errors encountered. RequestResponse is always set regardless of any errors being set

func (*RequestResponse) Body

func (r *RequestResponse) Body() string

func (*RequestResponse) Default

func (r *RequestResponse) Default() interface{}

func (*RequestResponse) JSON

func (r *RequestResponse) JSON() JSONFragment

func (*RequestResponse) MarshalJSON

func (r *RequestResponse) MarshalJSON() ([]byte, error)

func (*RequestResponse) Request

func (r *RequestResponse) Request() string

func (*RequestResponse) Resolve

func (r *RequestResponse) Resolve(key string) interface{}

func (*RequestResponse) Response

func (r *RequestResponse) Response() string

func (*RequestResponse) Status

func (*RequestResponse) StatusCode

func (r *RequestResponse) StatusCode() int

func (*RequestResponse) String

func (r *RequestResponse) String() string

func (*RequestResponse) URL

func (r *RequestResponse) URL() string

func (*RequestResponse) UnmarshalJSON

func (r *RequestResponse) UnmarshalJSON(data []byte) error

type RequestResponseStatus

type RequestResponseStatus string

RequestResponseStatus represents the status of a WebhookRequeset

const (
	// RRSuccess represents that the webhook was successful
	RRSuccess RequestResponseStatus = "success"

	// RRConnectionError represents that the webhook had a connection error
	RRConnectionError RequestResponseStatus = "connection_error"

	// RRResponseError represents that the webhook response had a non 2xx status code
	RRResponseError RequestResponseStatus = "response_error"
)

func (RequestResponseStatus) String

func (r RequestResponseStatus) String() string

type TimeFormat

type TimeFormat string

func (TimeFormat) String

func (tf TimeFormat) String() string

type Typed

type Typed interface {
	Type() string
}

type TypedEnvelope

type TypedEnvelope struct {
	Type string `json:"type"`
	Data []byte `json:"-"`
}

TypedEnvelope represents a json blob with a type property

func EnvelopeFromTyped

func EnvelopeFromTyped(typed Typed) (*TypedEnvelope, error)

func (*TypedEnvelope) MarshalJSON

func (e *TypedEnvelope) MarshalJSON() ([]byte, error)

func (*TypedEnvelope) UnmarshalJSON

func (e *TypedEnvelope) UnmarshalJSON(b []byte) (err error)

type ValidationErrors added in v0.4.0

type ValidationErrors []error

func NewValidationErrors added in v0.4.0

func NewValidationErrors(messages ...string) ValidationErrors

func (ValidationErrors) Error added in v0.4.0

func (e ValidationErrors) Error() string

Error returns a string representation of these validation errors

type VariableResolver

type VariableResolver interface {
	Resolve(key string) interface{}
	Default() interface{}
	String() string
}

VariableResolver defines the interface used by Excellent objects that can be indexed into

func NewMapResolver

func NewMapResolver(values map[string]interface{}) VariableResolver

NewMapResolver returns a simple resolver that resolves variables according to the values passed in

type XType

type XType int

XType is an an enumeration of the possible types we can deal with

func ToXAtom

func ToXAtom(env Environment, val interface{}) (interface{}, XType, error)

ToXAtom figures out the raw type of the passed in interface, returning that type

Jump to

Keyboard shortcuts

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