Categorygithub.com/gouniverse/dataobject
repositorypackage
0.3.0
Repository: https://github.com/gouniverse/dataobject.git
Documentation: pkg.go.dev

# README

Data Object Open in Gitpod

A data object is a special purpose structure that is designed to hold data and track the changes to allow efficient serialization to a data store.

It follows the following principles:

  1. Has a default, non-argument constructor
  2. Has a unique identifier (ID) allowing to safely find the object among any other
  3. All the fields are private, thus non-modifiable from outside
  4. The fields are only accessed via public setter (mutator) and getter (accessor) methods
  5. All changes are tracked, and returned on request as a map of type map[string]string
  6. All data can be returned on request as a map of type map[string]string

Any object can be considered a data object as long as it adheres to the above principles, regardless of its specific implementation.

The implementation in this repo is just one way to implement the above principles. Other variations are possible to suit specific needs.

The concept is a bit similar to a POJO and a Java Bean.

Usage

This is a full fledged example of a User data object taken from real life.

The example shows how to create new data object, set and get fields. Add helper methods to work with the fields.

Optional ORM-like relationship methods are also included. Use these with caution as these may create dependencies (i.e. with your services, repos, etc) that you may not want and need.

package models

import (
	"github.com/gouniverse/dataobject"
	"github.com/gouniverse/uid"
	"github.com/golang-module/carbon/v2"
)

// User is a data object
type User struct {
	dataobject.DataObject
}

// =============================  CONSTRUCTORS =============================

// NewUser instantiates a new user
func NewUser() *User {
	o := &User{}
	o.SetID(uid.HumanUid())
	o.SetStatus("active")
	o.SetCreatedAt(carbon.Now(carbon.UTC).ToDateTimeString(carbon.UTC))
	o.SetUpdatedAt(carbon.Now(carbon.UTC).ToDateTimeString(carbon.UTC))
	return o
}

// NewUserFromExistingData helper method to hydrate an existing user data object
func NewUserFromExistingData(data map[string]string) *User {
	o := &User{}
	o.Hydrate(data)
	return o
}

// ======================== RELATIONS/ORM (OPTIONAL) ===========================

func (o *User) Messages() []Messages {
	return NewMessageService.GetUserMessages(o.GetID())
}


func (o *User) Create() error {
	return NewUserService.Create(o)
}

func (o *User) Update() error {
	if !o.IsDirty() {
		return nil // object has not been changed
	}

	return NewUserService.Update(o)
}

// ================================ METHODS ====================================

func (o *User) IsActive() bool {
	return o.Status() == "active"
}

// ============================ GETTERS AND SETTERS ============================

func (o *User) CreatedAt() string {
	return o.Get("created_at")
}

func (o *User) CreatedAtCarbon() carbon.Carbon {
	return carbon.Parse(o.CreatedAt(), carbon.UTC)
}

func (o *User) SetCreatedAt(createdAt string) *User {
	o.Set("created_at", createdAt)
	return o
}

func (o *User) FirstName() string {
	return o.Get("first_name")
}

func (o *User) SetFirstName(firstName string) *User {
	o.Set("first_name", firstName)
	return o
}

func (o *User) LastName() string {
	return o.Get("last_name")
}

func (o *User) SetLastName(lastName string) *User {
	o.Set("last_name", lastName)
	return o
}

func (o *User) MiddleNames() string {
	return o.Get("middle_names")
}

func (o *User) SetMiddleNames(middleNames string) *User {
	o.Set("middle_names", middleNames)
	return o
}

func (o *User) Status() string {
	return o.Get("status")
}

func (o *User) SetStatus(status string) *User {
	o.Set("status", status)
	return o
}

func (o *User) UpdatedAt() string {
	return o.Get("updated_at")
}

func (o *User) UpdatedAtCarbon() carbon.Carbon {
	return carbon.Parse(o.UpdatedAt(), carbon.UTC)
}

func (o *User) SetUpdatedAt(updatedAt string) *User {
	o.Set("updated_at", updatedAt)
	return o
}

For an object using the above specifications

// Create new user with autogenerated default ID
user := NewUser()

// Create new user with already existing data (i.e. from database)
user := NewUserFromData(data)

// returns the ID of the object
id := user.ID()

// example setter method
user.SetFirstName("John")

// example getter method
firstName := user.FirstName()

// find if the object has been modified
isDirty := user.IsDirty()

// reurns the changed data
dataChanged := user.DataChanged()

// reurns all the data
data := user.Data()

Saving data

Saving the data is left to the end user, as it is specific for each data store.

Some stores (i.e. relational databases) allow to only change specific fields, which is why the DataChanged() getter method should be used to identify the changed fields, then only save the changes efficiently.

func SaveUserChanges(user User) bool {
    if !user.IsDirty() {
        return true
    }

    changedData := user.DataChanged()

    return save(changedData)
}

Other stores (i.e. document stores, file stores) save all the fields each time, which is where the Data() getter method should be used

func SaveFullUser(user User) bool {
    if !user.IsDirty() {
        return true
    }

    allData := user.Data()

    return save(allData)
}

Serialize to JSON

jsonString, err := user.ToJSON()


if err != nil {
    log.Fatal("Error serializing")
}

log.Println(jsonString)

Deserialize from JSON

user, err := NewDataObjectFromJSON(jsonString)

if err != nil {
    log.Fatal("Error deserializing")
}

user.Get("first_name")