utils

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2018 License: AGPL-3.0 Imports: 21 Imported by: 43

Documentation

Index

Constants

View Source
const (
	XTypeNil = iota
	XTypeString
	XTypeDecimal
	XTypeTime
	XTypeLocation
	XTypeBool
	XTypeError
	XTypeStringSlice
	XTypeDecimalSlice
	XTypeTimeSlice
	XTypeBoolSlice
	XTypeMap
)

primitive types we convert to

View Source
const (
	DateFormatYearMonthDay DateFormat = "yyyy-MM-dd"
	DateFormatMonthDayYear DateFormat = "MM-dd-yyyy"
	DateFormatDayMonthYear DateFormat = "dd-MM-yyyy"

	TimeFormatHourMinute           TimeFormat = "hh:mm"
	TimeFormatHourMinuteAmPm       TimeFormat = "hh:mm tt"
	TimeFormatHourMinuteSecond     TimeFormat = "HH:mm:ss"
	TimeFormatHourMinuteSecondAmPm TimeFormat = "hh:mm:ss tt"
)

standard date and time formats

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)

DateToUTCRange returns the UTC time range of the given day

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

IsMap returns whether the given object is a map

func IsNil added in v0.4.0

func IsNil(v interface{}) bool

IsNil returns whether the given object is nil or an interface to a nil

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 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 SetUUIDGenerator added in v0.6.0

func SetUUIDGenerator(generator UUIDGenerator)

SetUUIDGenerator sets the generator used by UUID4()

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

UnmarshalAndValidate is a convenience function to unmarshal an object and validate it

func UnmarshalArray added in v0.4.0

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

UnmarshalArray unmarshals an array of objects from the given JSON

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

DateFormat a date format 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

func ReadEnvironment added in v0.4.0

func ReadEnvironment(data json.RawMessage) (Environment, error)

ReadEnvironment reads an environment from the given JSON

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 value of this JSON fragment when it is the result of an expression

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 given key when this JSON fragment is referenced in an expression

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

LanguageList is a list of languages

func (LanguageList) RemoveDuplicates added in v0.4.0

func (ll LanguageList) RemoveDuplicates() LanguageList

RemoveDuplicates returns a new language list with duplicates removed

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

Aliases gets the aliases of this location

func (*Location) Children added in v0.4.0

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

Children gets the children of this location

func (*Location) ID added in v0.4.0

func (b *Location) ID() LocationID

ID gets the id of this location

func (*Location) Level added in v0.4.0

func (b *Location) Level() LocationLevel

Level gets the level of this location

func (*Location) Name added in v0.4.0

func (b *Location) Name() string

Name gets the name of this location

func (*Location) Parent added in v0.4.0

func (b *Location) Parent() *Location

Parent gets the parent of this 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

func (*LocationHierarchy) Root added in v0.6.0

func (s *LocationHierarchy) Root() *Location

Root gets the root location of this hierarchy

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

Body returns the response body

func (*RequestResponse) Default

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

Default returns the value of this webhook when it is the result of an expression

func (*RequestResponse) JSON

func (r *RequestResponse) JSON() JSONFragment

JSON returns the response as a JSON fragment

func (*RequestResponse) MarshalJSON

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

MarshalJSON marshals this request response into JSON

func (*RequestResponse) Request

func (r *RequestResponse) Request() string

Request returns the request trace

func (*RequestResponse) Resolve

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

Resolve resolves the given key when this webhook is referenced in an expression

func (*RequestResponse) Response

func (r *RequestResponse) Response() string

Response returns the response trace

func (*RequestResponse) Status

Status returns the response status message

func (*RequestResponse) StatusCode

func (r *RequestResponse) StatusCode() int

StatusCode returns the response status code

func (*RequestResponse) String

func (r *RequestResponse) String() string

func (*RequestResponse) URL

func (r *RequestResponse) URL() string

URL returns the full URL

func (*RequestResponse) UnmarshalJSON

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

UnmarshalJSON unmarshals a request response from the given JSON

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 SeededUUID4Generator added in v0.6.0

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

SeededUUID4Generator generates a seedable random v4 UUID using math/rand

func NewSeededUUID4Generator added in v0.6.0

func NewSeededUUID4Generator(seed int64) *SeededUUID4Generator

NewSeededUUID4Generator creates a new SeededUUID4Generator from the given seed

func (*SeededUUID4Generator) Next added in v0.6.0

func (g *SeededUUID4Generator) Next() UUID

Next returns the next random UUID

type TimeFormat

type TimeFormat string

TimeFormat a time format string

func (TimeFormat) String

func (tf TimeFormat) String() string

type Typed

type Typed interface {
	Type() string
}

Typed is an interface of objects that are marshalled as typed envelopes

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)

EnvelopeFromTyped marshals the give object into a typed envelope

func (*TypedEnvelope) MarshalJSON

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

MarshalJSON marshals this envelope into JSON

func (*TypedEnvelope) UnmarshalJSON

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

UnmarshalJSON unmarshals a typed envelope from the given JSON

type UUID added in v0.6.0

type UUID string

UUID is a 36 character UUID

func NewUUID added in v0.6.0

func NewUUID() UUID

NewUUID returns a new NewUUID

type UUIDGenerator added in v0.6.0

type UUIDGenerator interface {
	Next() UUID
}

UUIDGenerator is something that can generate a UUID

var DefaultUUIDGenerator UUIDGenerator = defaultUUID4Generator{}

DefaultUUIDGenerator is the default generator for calls to NewUUID

type ValidationErrors added in v0.4.0

type ValidationErrors []error

ValidationErrors combines multiple validation errors as a single error

func NewValidationErrors added in v0.4.0

func NewValidationErrors(messages ...string) ValidationErrors

NewValidationErrors creates new ValidationErrors fromn the given error messages

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