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
| type TimeMixin struct { mixin.Schema } func (TimeMixin) Fields() []ent.Field { return []ent.Field{ field.Time("created_at").Immutable().Default(time.Now), field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), field.Time("deleted_at").Optional(), }} type softDeleteKey struct{} func SkipSoftDelete(parent context.Context) context.Context { return context.WithValue(parent, softDeleteKey{}, true) } func (t TimeMixin) Interceptors() []ent.Interceptor { return []ent.Interceptor{ intercept.TraverseFunc(func(ctx context.Context, q intercept.Query) error { if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip { return nil } t.P(q) return nil }), } } func (t TimeMixin) Hooks() []ent.Hook { return []ent.Hook{ hook.On( func(next ent.Mutator) ent.Mutator { return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip { return next.Mutate(ctx, m) } mx, ok := m.(interface { SetOp(ent.Op) Client() *gen.Client SetDeletedAt(time.Time) WhereP(...func(*sql.Selector)) }) if !ok { return nil, fmt.Errorf("unexpected mutation types %T", m) } t.P(mx mx.SetOp(ent.OpUpdate) mx.SetDeletedAt(time.Now()) return mx.Client().Mutate(ctx, m) }) }, ent.OpDeleteOne|ent.OpDelete, )} } func (t TimeMixin) P(w interface{ WhereP(...func(*sql.Selector)) }) { w.WhereP( sql.FieldIsNull(t.Fields()[2].Descriptor().Name), ) }
|