schema/mixin: add support for mixed-in annotations

This commit is contained in:
Ariel Mashraki
2020-10-11 21:06:10 +03:00
committed by Ariel Mashraki
parent 85c4999472
commit c8a6527612
5 changed files with 38 additions and 8 deletions

3
ent.go
View File

@@ -153,6 +153,9 @@ type (
// Policy returns a privacy policy to add to the schema.
// Note that mixin policy are executed before schema policy.
Policy() Policy
// Annotations returns a list of schema annotations to add
// to the schema annotations.
Annotations() []schema.Annotation
}
// The Policy type defines the write privacy policy of an entity.

File diff suppressed because one or more lines are too long

View File

@@ -158,12 +158,13 @@ func MarshalSchema(schema ent.Interface) (b []byte, err error) {
Name: indirect(reflect.TypeOf(schema)).Name(),
Annotations: make(map[string]interface{}),
}
for _, at := range schema.Annotations() {
s.Annotations[at.Name()] = at
}
if err := s.loadMixin(schema); err != nil {
return nil, fmt.Errorf("schema %q: %v", s.Name, err)
}
// Schema annotations override mixed-in annotations.
for _, at := range schema.Annotations() {
s.Annotations[at.Name()] = at
}
if err := s.loadFields(schema); err != nil {
return nil, fmt.Errorf("schema %q: %v", s.Name, err)
}
@@ -263,6 +264,9 @@ func (s *Schema) loadMixin(schema ent.Interface) error {
MixinIndex: i,
})
}
for _, at := range mx.Annotations() {
s.Annotations[at.Name()] = at
}
}
return nil
}

View File

@@ -30,14 +30,34 @@ func (OrderConfig) Name() string {
return "order_config"
}
func (o *OrderConfig) MarshalJSON() ([]byte, error) {
return json.Marshal(*o)
type IDConfig struct {
TagName string
}
func (IDConfig) Name() string {
return "id_config"
}
type AnnotationMixin struct {
mixin.Schema
}
func (AnnotationMixin) Annotations() []schema.Annotation {
return []schema.Annotation{
IDConfig{TagName: "id tag"},
}
}
type User struct {
ent.Schema
}
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
AnnotationMixin{},
}
}
func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
OrderConfig{FieldName: "type annotations"},
@@ -110,7 +130,7 @@ func TestMarshalSchema(t *testing.T) {
schema, err := UnmarshalSchema(buf)
require.NoError(t, err)
require.Equal(t, "User", schema.Name)
require.Len(t, schema.Annotations, 1)
require.Len(t, schema.Annotations, 2)
ant := schema.Annotations["order_config"].(map[string]interface{})
require.Equal(t, ant["FieldName"], "type annotations")

View File

@@ -36,6 +36,9 @@ func (Schema) Hooks() []ent.Hook { return nil }
// Policy of the mixin.
func (Schema) Policy() ent.Policy { return nil }
// Annotations of the mixin.
func (Schema) Annotations() []schema.Annotation { return nil }
// time mixin must implement `Mixin` interface.
var _ ent.Mixin = (*Schema)(nil)