golymorph

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2023 License: MIT Imports: 8 Imported by: 0

README

golymorph Pipeline Tests Status Godoc

The golymorph module enables resolving polymorphic typing at runtime. It's usually used in conjunction with JSON parsing and the mapstructure module. In fact, this module takes the use case of mapstructure and takes it a step further by allowing the user to define a custom type resolver function.

Installation

Standard go get:

go get github.com/SoulKa/golymorph

Usage & Example

For usage and examples see the Godoc.

package main

import (
	"fmt"
	"github.com/SoulKa/golymorph"
	"reflect"
)

func main() {
	// get a JSON that contains a payload with a type field that determines the type of the payload
	alertEventJson := `{ "timestamp": "2023-11-27T22:14:09+00:00", "payload": { "type": "alert", "message": "something is broken!" } }`

	// the parent type that contains the polymorphic payload
	type Event struct {
		Timestamp string
		Payload   any
	}

	// the polymorphic child types
	type AlertPayload struct {
		Type    string
		Message string
	}
	type PingPayload struct {
		Type string
		Ip   string
	}

	// define a mapping from the type value to the type of the payload
	typeMap := golymorph.TypeMap{
		"alert": reflect.TypeOf(AlertPayload{}),
		"ping":  reflect.TypeOf(PingPayload{}),
	}

	// create a TypeResolver that assigns the type of the payload based on the type field
	err, resolver := golymorph.NewPolymorphismBuilder().
		DefineTypeAt("payload").
		UsingTypeMap(typeMap).
		WithDiscriminatorAt("type").
		Build()
	if err != nil {
		panic(fmt.Sprintf("error building polymorpher: %s", err))
	}

	// create a new event
	var event Event
	if err := golymorph.UnmarshalJSON(resolver, []byte(alertEventJson), &event); err != nil {
		panic(fmt.Sprintf("error unmarshalling event: %s", err))
	}

	// continue to work with the event
	fmt.Printf("event: %+v\n", event)
	fmt.Printf("event payload: %T %+v\n", event.Payload, event.Payload.(AlertPayload))
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Decode

func Decode(resolver TypeResolver, source map[string]any, output any) error

Decode decodes the given source map into the given output object using the given TypeResolver and mapstructure.

func UnmarshalJSON

func UnmarshalJSON(resolver TypeResolver, data []byte, output any) error

UnmarshalJSON unmarshals the given JSON data into the given output object using the given TypeResolver.

Types

type Polymorphism

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

type PolymorphismBuilderBase

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

func (*PolymorphismBuilderBase) DefineTypeAt

func (*PolymorphismBuilderBase) UsingRule

func (*PolymorphismBuilderBase) UsingTypeMap

type PolymorphismBuilderDiscriminatorKeyDefiner

type PolymorphismBuilderDiscriminatorKeyDefiner interface {
	WithDiscriminatorAt(discriminatorKey string) PolymorphismBuilderFinalizer
}

type PolymorphismBuilderEmpty

type PolymorphismBuilderEmpty interface {
	DefineTypeAt(targetPath string) PolymorphismBuilderStrategySelector
}

func NewPolymorphismBuilder

func NewPolymorphismBuilder() PolymorphismBuilderEmpty

type PolymorphismBuilderFinalizer

type PolymorphismBuilderFinalizer interface {
	Build() (error, TypeResolver)
}

type PolymorphismBuilderRuleAdder

type PolymorphismBuilderRuleAdder interface {
	UsingRule(rule Rule) PolymorphismBuilderRuleAdder
	Build() (error, TypeResolver)
}

type PolymorphismBuilderStrategySelector

type PolymorphismBuilderStrategySelector interface {
	UsingRule(rule Rule) PolymorphismBuilderRuleAdder
	UsingTypeMap(typeMap TypeMap) PolymorphismBuilderDiscriminatorKeyDefiner
}

type PolymorphismRuleBuilder

type PolymorphismRuleBuilder struct {
	PolymorphismBuilderBase
	// contains filtered or unexported fields
}

func (*PolymorphismRuleBuilder) Build

func (*PolymorphismRuleBuilder) UsingRule

type PolymorphismTypeMapBuilder

type PolymorphismTypeMapBuilder struct {
	PolymorphismBuilderBase
	// contains filtered or unexported fields
}

func (*PolymorphismTypeMapBuilder) Build

func (*PolymorphismTypeMapBuilder) WithDiscriminatorAt

func (b *PolymorphismTypeMapBuilder) WithDiscriminatorAt(discriminatorKey string) PolymorphismBuilderFinalizer

type Rule

type Rule struct {
	// ValuePath is the path to the value in the source to compare.
	ValuePath objectpath.ObjectPath
	// ComparatorFunction is the function to use to compare the value at ValuePath to.
	ComparatorFunction func(any) bool
	// NewType is the type to assign to the target if the rule matches.
	NewType reflect.Type
}

Rule is a rule for a polymorphism mapper.

func (*Rule) Matches

func (r *Rule) Matches(source any) (error, bool)

Matches returns true if the source matches the rule.

type RuleBuilder

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

RuleBuilder is a builder for a polymorphism rule.

func (*RuleBuilder) Build

func (b *RuleBuilder) Build() ([]error, Rule)

Build builds the Rule and returns the errors encountered while building.

func (*RuleBuilder) IsEqualTo

func (b *RuleBuilder) IsEqualTo(value any) RuleBuilderTypeAssigner

IsEqualTo sets the value to compare to.

func (*RuleBuilder) Matches

func (b *RuleBuilder) Matches(comparator func(any) bool) RuleBuilderTypeAssigner

Matches sets the function to use to compare the value at ValuePath to.

func (*RuleBuilder) ThenAssignType

func (b *RuleBuilder) ThenAssignType(newType reflect.Type) RuleBuilderFinalizer

ThenAssignType sets the type to assign to the target if the rule matches.

func (*RuleBuilder) WhenValueAt

func (b *RuleBuilder) WhenValueAt(valuePath objectpath.ObjectPath) RuleBuilderConditionSetter

WhenValueAt sets the path to the value in the source to compare.

func (*RuleBuilder) WhenValueAtPathString

func (b *RuleBuilder) WhenValueAtPathString(valuePath string) RuleBuilderConditionSetter

WhenValueAtPathString sets the path to the value in the source to compare.

type RuleBuilderBase

type RuleBuilderBase interface {
	WhenValueAt(valuePath objectpath.ObjectPath) RuleBuilderConditionSetter
	WhenValueAtPathString(valuePath string) RuleBuilderConditionSetter
}

func NewRuleBuilder

func NewRuleBuilder() RuleBuilderBase

NewRuleBuilder creates a new RuleBuilder. It enables a fluent interface for building a Rule.

type RuleBuilderConditionSetter

type RuleBuilderConditionSetter interface {
	IsEqualTo(value any) RuleBuilderTypeAssigner
	Matches(comparator func(any) bool) RuleBuilderTypeAssigner
}

type RuleBuilderFinalizer

type RuleBuilderFinalizer interface {
	Build() ([]error, Rule)
}

type RuleBuilderTypeAssigner

type RuleBuilderTypeAssigner interface {
	ThenAssignType(newType reflect.Type) RuleBuilderFinalizer
}

type RulePolymorphism

type RulePolymorphism struct {
	Polymorphism
	// contains filtered or unexported fields
}

RulePolymorphism is a mapper that assigns a target type based on the given rules

func (*RulePolymorphism) AssignTargetType

func (p *RulePolymorphism) AssignTargetType(source any, target any) error

type TypeMap

type TypeMap map[any]reflect.Type

type TypeMapPolymorphism

type TypeMapPolymorphism struct {
	Polymorphism
	// contains filtered or unexported fields
}

TypeMapPolymorphism is a mapper that assigns a target type based on a discriminator value and a type map

func (*TypeMapPolymorphism) AssignTargetType

func (p *TypeMapPolymorphism) AssignTargetType(source any, target any) error

type TypeResolver

type TypeResolver interface {
	// AssignTargetType assigns the determined type to target based on the polymorphism rules. The matching rule with the
	// highest priority is used. If no rule matches, the target type is not changed. The source and target must be pointers.
	// If no matching type can be determined, an error.UnresolvedTypeError is returned.
	AssignTargetType(source any, target any) error
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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