changeset

package module
v0.0.0-...-664df8a Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2020 License: MIT Imports: 13 Imported by: 0

README

changeset

GoDoc Build Status Go Report Card Gocover

Changeset mutator for REL. Changesets allow filtering, casting, validation and definition of constraints when manipulating structs.

Install

go get github.com/Fs02/changeset

Example

package main

import (
	"time"

	"github.com/Fs02/rel"
	"github.com/Fs02/rel/adapter/mysql"
	"github.com/Fs02/changeset"
	"github.com/Fs02/changeset/params"
)

type Product struct {
	ID        int
	Name      string
	Price     int
	CreatedAt time.Time
	UpdatedAt time.Time
}

// ChangeProduct prepares data before database operation.
// Such as casting value to appropriate types and perform validations.
func ChangeProduct(product interface{}, params params.Params) *changeset.Changeset {
	ch := changeset.Cast(product, params, []string{"name", "price"})
	changeset.ValidateRequired(ch, []string{"name", "price"})
	changeset.ValidateMin(ch, "price", 100)
	return ch
}

func main() {
    // initialize mysql adapter.
    adapter, _ := mysql.Open(dsn)
    defer adapter.Close()

    // initialize rel's repo.
    repo := rel.New(adapter)

	var product Product

	// Inserting Products.
	// Changeset is used when creating or updating your data.
	ch := ChangeProduct(product, params.Map{
		"name":  "shampoo",
		"price": 1000,
	})

	if ch.Error() != nil {
		// handle error
	}

	// Changeset can also be created directly from json string.
	jsonch := ChangeProduct(product, params.ParseJSON(`{
		"name":  "soap",
		"price": 2000,
	}`))

	// Create products with changeset and return the result to &product,
	if err := repo.Insert(context.TODO(), &product, ch); err != nil {
		// handle error
	}
}

License

Released under the MIT License

Documentation

Overview

Package changeset used to cast and validate data before saving it to the database.

Package changeset used to cast and validate data before saving it to the database.

Index

Examples

Constants

This section is empty.

Variables

View Source
var CastAssocErrorMessage = "{field} is invalid"

CastAssocErrorMessage is the default error message for CastAssoc when its invalid.

View Source
var CastAssocRequiredMessage = "{field} is required"

CastAssocRequiredMessage is the default error message for CastAssoc when its missing.

View Source
var CastErrorMessage = "{field} is invalid"

CastErrorMessage is the default error message for Cast.

View Source
var CheckConstraintMessage = "{field} is invalid"

CheckConstraintMessage is the default error message for CheckConstraint.

View Source
var ForeignKeyConstraintMessage = "does not exist"

ForeignKeyConstraintMessage is the default error message for ForeignKeyConstraint.

View Source
var PutAssocErrorMessage = "{field} is invalid"

PutAssocErrorMessage is the default error message for PutAssoc.

View Source
var PutChangeErrorMessage = "{field} is invalid"

PutChangeErrorMessage is the default error message for PutChange.

View Source
var PutDefaultErrorMessage = "{field} is invalid"

PutDefaultErrorMessage is the default error message for PutDefault.

View Source
var UniqueConstraintMessage = "{field} has already been taken"

UniqueConstraintMessage is the default error message for UniqueConstraint.

View Source
var ValidateExclusionErrorMessage = "{field} must not be any of {values}"

ValidateExclusionErrorMessage is the default error message for ValidateExclusion.

View Source
var ValidateInclusionErrorMessage = "{field} must be one of {values}"

ValidateInclusionErrorMessage is the default error message for ValidateInclusion.

View Source
var ValidateMaxErrorMessage = "{field} must be less than {max}"

ValidateMaxErrorMessage is the default error message for ValidateMax.

View Source
var ValidateMinErrorMessage = "{field} must be more than {min}"

ValidateMinErrorMessage is the default error message for ValidateMin.

View Source
var ValidatePatternErrorMessage = "{field}'s format is invalid"

ValidatePatternErrorMessage is the default error message for ValidatePattern.

View Source
var ValidateRangeErrorMessage = "{field} must be between {min} and {max}"

ValidateRangeErrorMessage is the default error message for ValidateRange.

View Source
var ValidateRegexpErrorMessage = "{field}'s format is invalid"

ValidateRegexpErrorMessage is the default error message for ValidateRegexp.

View Source
var ValidateRequiredErrorMessage = "{field} is required"

ValidateRequiredErrorMessage is the default error message for ValidateRequired.

Functions

func AddError

func AddError(ch *Changeset, field string, message string)

AddError adds an error to changeset.

ch := changeset.Cast(user, params, fields)
changeset.AddError(ch, "field", "error")
ch.Errors() // []errors.Error{{Field: "field", Message: "error"}}

func ApplyString

func ApplyString(ch *Changeset, field string, fn func(string) string)

ApplyString apply a function for string value.

func CastAssoc

func CastAssoc(ch *Changeset, field string, fn ChangeFunc, opts ...Option)

CastAssoc casts association changes using changeset function. Repo insert or update won't persist any changes generated by CastAssoc.

func CheckConstraint

func CheckConstraint(ch *Changeset, field string, opts ...Option)

CheckConstraint adds an unique constraint to changeset.

func DeleteChange

func DeleteChange(ch *Changeset, field string)

DeleteChange from changeset.

func EscapeString

func EscapeString(ch *Changeset, fields ...string)

EscapeString escapes special characters like "<" to become "&lt;". this is helper for html.EscapeString

func ForeignKeyConstraint

func ForeignKeyConstraint(ch *Changeset, field string, opts ...Option)

ForeignKeyConstraint adds an unique constraint to changeset.

func PutAssoc

func PutAssoc(ch *Changeset, field string, value interface{}, opts ...Option)

PutAssoc to changeset.

func PutChange

func PutChange(ch *Changeset, field string, value interface{}, opts ...Option)

PutChange to changeset.

func PutDefault

func PutDefault(ch *Changeset, field string, value interface{}, opts ...Option)

PutDefault to changeset.

func UnescapeString

func UnescapeString(ch *Changeset, field string)

UnescapeString unescapes entities like "&lt;" to become "<". this is helper for html.UnescapeString.

func UniqueConstraint

func UniqueConstraint(ch *Changeset, field string, opts ...Option)

UniqueConstraint adds an unique constraint to changeset.

func ValidateExclusion

func ValidateExclusion(ch *Changeset, field string, values []interface{}, opts ...Option)

ValidateExclusion validates a change is not included in the given values.

func ValidateInclusion

func ValidateInclusion(ch *Changeset, field string, values []interface{}, opts ...Option)

ValidateInclusion validates a change is included in the given values.

func ValidateMax

func ValidateMax(ch *Changeset, field string, max int, opts ...Option)

ValidateMax validates the value of given field is not larger than max. Validation can be performed against string, slice and numbers.

func ValidateMin

func ValidateMin(ch *Changeset, field string, min int, opts ...Option)

ValidateMin validates the value of given field is not smaller than min. Validation can be performed against string, slice and numbers.

func ValidatePattern

func ValidatePattern(ch *Changeset, field string, pattern string, opts ...Option)

ValidatePattern validates the value of given field to match given pattern.

func ValidateRange

func ValidateRange(ch *Changeset, field string, min int, max int, opts ...Option)

ValidateRange validates the value of given field is not larger than max and not smaller than min. Validation can be performed against string, slice and numbers.

func ValidateRegexp

func ValidateRegexp(ch *Changeset, field string, exp *regexp.Regexp, opts ...Option)

ValidateRegexp validates the value of given field to match given regexp.

func ValidateRequired

func ValidateRequired(ch *Changeset, fields []string, opts ...Option)

ValidateRequired validates that one or more fields are present in the changeset. It'll add error to changeset if field in the changes is nil or string made only of whitespace.

Types

type ChangeFunc

type ChangeFunc func(interface{}, params.Params) *Changeset

ChangeFunc is changeset function.

type Changeset

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

Changeset used to cast and validate data before saving it to the database.

func Cast

func Cast(data interface{}, params params.Params, fields []string, opts ...Option) *Changeset

Cast params as changes for the given data according to the permitted fields. Returns a new changeset. params will only be added as changes if it does not have the same value as the field in the data.

Example
type User struct {
	ID   int
	Name string
}

user := User{}
input := params.Map{
	"id":   1,
	"name": "name",
}

ch := Cast(user, input, []string{"name"})
fmt.Println(ch.Changes())
Output:

map[name:name]
Example (InvalidType)
type User struct {
	ID   int
	Name string
}

user := User{}
input := params.Map{
	"id":   1,
	"name": true,
}

ch := Cast(user, input, []string{"name"})
fmt.Println(ch.Error())
Output:

name is invalid
Example (InvalidTypeWithCustomError)
type User struct {
	ID   int
	Name string
}

user := User{}
input := params.Map{
	"id":   1,
	"name": true,
}

ch := Cast(user, input, []string{"name"}, Message("{field} tidak valid"))
fmt.Println(ch.Error())
Output:

name tidak valid

func Change

func Change(schema interface{}, changes ...map[string]interface{}) *Changeset

Change make a new changeset without changes and build from given schema. Returns new Changeset.

func Convert

func Convert(data interface{}) *Changeset

Convert a struct as changeset, every field's value will be treated as changes. Returns a new changeset.

func (*Changeset) Apply

func (c *Changeset) Apply(doc *rel.Document, mut *rel.Mutation)

Apply mutation.

func (Changeset) Changes

func (c Changeset) Changes() map[string]interface{}

Changes of changeset.

func (Changeset) Constraints

func (c Changeset) Constraints() Constraints

Constraints of changeset.

func (Changeset) Error

func (c Changeset) Error() error

Error of changeset, returns the first error if any.

func (Changeset) Errors

func (c Changeset) Errors() []error

Errors of changeset.

func (Changeset) Fetch

func (c Changeset) Fetch(field string) interface{}

Fetch a change or value from changeset.

func (Changeset) Get

func (c Changeset) Get(field string) interface{}

Get a change from changeset.

func (Changeset) Types

func (c Changeset) Types() map[string]reflect.Type

Types of changeset.

func (Changeset) Values

func (c Changeset) Values() map[string]interface{}

Values of changeset.

type Constraint

type Constraint struct {
	Field   string
	Message string
	Code    int
	Name    string
	Exact   bool
	Type    rel.ConstraintType
}

Constraint defines information to infer constraint error.

type Constraints

type Constraints []Constraint

Constraints is slice of Constraint

func (Constraints) GetError

func (constraints Constraints) GetError(err error) error

GetError converts error based on constraints. If the original error is constraint error, and it's defined in the constraint list, then it'll be updated with constraint's message. If the original error is constraint error but not defined in the constraint list, it'll be converted to unexpected error. else it'll not modify the error.

type Error

type Error struct {
	Message string `json:"message"`
	Field   string `json:"field,omitempty"`
	Code    int    `json:"code,omitempty"`
	Err     error  `json:"-"`
}

Error struct.

func (Error) Error

func (e Error) Error() string

Error prints error message.

func (Error) Unwrap

func (e Error) Unwrap() error

Unwrap internal error.

type Option

type Option func(*Options)

Option for changeset operation.

func ChangeOnly

func ChangeOnly(changeOnly bool) Option

ChangeOnly is used to define if validate is only check change

func Code

func Code(code int) Option

Code for changeset operation's error.

func EmptyValues

func EmptyValues(values ...interface{}) Option

EmptyValues defines list of empty values when casting. default to [""]

func Exact

func Exact(exact bool) Option

Exact is used to define how index name is matched.

func Message

func Message(message string) Option

Message for changeset operation's error.

func Name

func Name(name string) Option

Name is used to define index name of constraints.

func Required

func Required(required bool) Option

Required is used to define whether an assoc needs to be required or not.

func SourceField

func SourceField(field string) Option

SourceField to define used field name in params.

type Options

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

Options applicable to changeset.

Directories

Path Synopsis
Package params defines different types of params used for changeset input.
Package params defines different types of params used for changeset input.

Jump to

Keyboard shortcuts

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