7575 StateMappingOpt func (* StateMapping , StateMappings )
7676)
7777
78- func mapKey (entry interface {}) string {
79- return reflect .TypeOf (entry ).String ()
78+ // mapKey schema string representation
79+ func mapKey (schema interface {}) string {
80+ return reflect .TypeOf (schema ).String ()
8081}
8182
8283func (smm StateMappings ) Add (schema interface {}, opts ... StateMappingOpt ) StateMappings {
@@ -96,10 +97,11 @@ func (smm StateMappings) Add(schema interface{}, opts ...StateMappingOpt) StateM
9697func applyStateMappingDefaults (sm * StateMapping ) {
9798 // default namespace based on type name
9899 if len (sm .namespace ) == 0 {
99- sm .namespace = SchemaNamespace ( sm .schema )
100+ sm .namespace = sm .DefaultNamespace ( )
100101 }
101102}
102103
104+ // SchemaNamespace produces string representation of Schema type
103105func SchemaNamespace (schema interface {}) state.Key {
104106 t := reflect .TypeOf (schema ).String ()
105107 return state.Key {t [strings .Index (t , `.` )+ 1 :]}
@@ -108,18 +110,15 @@ func SchemaNamespace(schema interface{}) state.Key {
108110// Get mapper for mapped entry
109111func (smm StateMappings ) Get (entry interface {}) (StateMapper , error ) {
110112 switch id := entry .(type ) {
113+ // entry is Key, namespace is first element of key
111114 case []string :
112115 return smm .GetByNamespace (id [0 :1 ])
113116 default :
114- m , ok := smm [mapKey (entry )]
115- if ! ok {
116- return nil , fmt .Errorf (`%s: %s` , ErrStateMappingNotFound , mapKey (entry ))
117- }
118- return m , nil
117+ return smm .GetBySchema (entry )
119118 }
120119}
121120
122- // Get mapper by string namespace. It can be used in block explorer: we know state key, but don't know
121+ // GetByNamespace returns mapper by string namespace. It can be used in block explorer: we know state key, but don't know
123122// type actually mapped to state
124123func (smm StateMappings ) GetByNamespace (namespace state.Key ) (StateMapper , error ) {
125124 for _ , m := range smm {
@@ -130,6 +129,14 @@ func (smm StateMappings) GetByNamespace(namespace state.Key) (StateMapper, error
130129 return nil , fmt .Errorf (`%s: %s` , ErrStateMappingNotFound , namespace )
131130}
132131
132+ func (smm StateMappings ) GetBySchema (schema interface {}) (StateMapper , error ) {
133+ m , ok := smm [mapKey (schema )]
134+ if ! ok {
135+ return nil , fmt .Errorf (`%s: %s` , ErrStateMappingNotFound , mapKey (schema ))
136+ }
137+ return m , nil
138+ }
139+
133140func (smm StateMappings ) Exists (entry interface {}) bool {
134141 _ , err := smm .Get (entry )
135142 return err == nil
@@ -167,6 +174,10 @@ func (sm *StateMapping) Namespace() state.Key {
167174 return sm .namespace
168175}
169176
177+ func (sm * StateMapping ) DefaultNamespace () state.Key {
178+ return SchemaNamespace (sm .schema )
179+ }
180+
170181func (sm * StateMapping ) Indexes () []* StateIndex {
171182 return sm .indexes
172183}
0 commit comments