Skip to content

Commit

Permalink
Merge pull request #420 from MUzairS15/MUzairS15/utility
Browse files Browse the repository at this point in the history
Add utility functions for type casting
  • Loading branch information
MUzairS15 committed Nov 27, 2023
2 parents f8ee397 + d15663e commit 0133432
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 5 deletions.
10 changes: 5 additions & 5 deletions broker/nats/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import (
)

const (
ErrConnectCode = "11000"
ErrEncodedConnCode = "11000"
ErrPublishCode = "11001"
ErrPublishRequestCode = "11001"
ErrQueueSubscribeCode = "11001"
ErrConnectCode = "11103"
ErrEncodedConnCode = "11104"
ErrPublishCode = "11105"
ErrPublishRequestCode = "11101"
ErrQueueSubscribeCode = "11102"
)

func ErrConnect(err error) error {
Expand Down
5 changes: 5 additions & 0 deletions helpers/component_info.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "meshkit",
"type": "library",
"next_error_code": 11106
}
6 changes: 6 additions & 0 deletions utils/error.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package utils

import (
"fmt"
"reflect"
"strconv"

Expand Down Expand Up @@ -28,6 +29,7 @@ var (
ErrYamlToCueCode = "11086"
ErrJsonSchemaToCueCode = "11087"
ErrCueLookupCode = "11089"
ErrTypeCastCode = "11100"
)

func ErrCueLookup(err error) error {
Expand Down Expand Up @@ -108,3 +110,7 @@ func ErrGettingLatestReleaseTag(err error) error {
[]string{"Make sure Github is reachable", "Make sure a valid response is available on github.com/<org>/<repo>/releases/stable"},
)
}

func ErrTypeCast(valType string) error {
return errors.New(ErrTypeCastCode, errors.Alert, []string{"invaid type assertion requested"}, []string{fmt.Sprintf("The underlying type of the interface is %s", valType)}, []string{"The interface type is not compatible with the request type cast"}, []string{"use correct data type for type casting"})
}
23 changes: 23 additions & 0 deletions utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"os"
"os/user"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strconv"
Expand Down Expand Up @@ -245,3 +246,25 @@ func Contains[G []K, K comparable](slice G, ele K) bool {
}
return false
}


func Cast[K any](val interface{}) (K, error) {
assertedValue, ok := val.(K)
if !ok {
return assertedValue, ErrTypeCast(reflect.TypeOf(val).Name())
}
return assertedValue, nil
}

func MarshalAndUnmarshal[fromType any, toType any](val fromType) (unmarshalledvalue toType, err error){
data, err := Marshal(val)
if err != nil {
return
}

err = Unmarshal(data, &unmarshalledvalue)
if err != nil {
return
}
return
}

0 comments on commit 0133432

Please sign in to comment.