This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
generated from mrz1836/go-template
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
model_ids.go
89 lines (73 loc) · 1.72 KB
/
model_ids.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package bux
import (
"database/sql/driver"
"encoding/json"
"fmt"
"github.com/99designs/gqlgen/graphql"
"github.com/BuxOrg/bux/datastore"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
// ValueTypeString is the value type "string"
const ValueTypeString = "string"
// IDs are string ids saved as an array
type IDs []string
// GormDataType type in gorm
func (i IDs) GormDataType() string {
return gormTypeText
}
// Scan scan value into JSON, implements sql.Scanner interface
func (i *IDs) Scan(value interface{}) error {
if value == nil {
return nil
}
xType := fmt.Sprintf("%T", value)
var byteValue []byte
if xType == ValueTypeString {
byteValue = []byte(value.(string))
} else {
byteValue = value.([]byte)
}
return json.Unmarshal(byteValue, &i)
}
// Value return json value, implement driver.Valuer interface
func (i IDs) Value() (driver.Value, error) {
if i == nil {
return nil, nil
}
marshal, err := json.Marshal(i)
if err != nil {
return nil, err
}
return string(marshal), nil
}
// MarshalIDs will unmarshal the custom type
func MarshalIDs(i IDs) graphql.Marshaler {
if i == nil {
return graphql.Null
}
return graphql.MarshalAny(i)
}
// GormDBDataType the gorm data type for metadata
func (IDs) GormDBDataType(db *gorm.DB, _ *schema.Field) string {
if db.Dialector.Name() == datastore.Postgres {
return datastore.JSONB
}
return datastore.JSON
}
// UnmarshalIDs will marshal the custom type
func UnmarshalIDs(v interface{}) (IDs, error) {
if v == nil {
return nil, nil
}
// Try to unmarshal
ids, err := graphql.UnmarshalAny(v)
if err != nil {
return nil, err
}
// Cast interface back to IDs (safely)
if idCast, ok := ids.(IDs); ok {
return idCast, nil
}
return nil, ErrCannotConvertToIDs
}