Files
ent/entc/gen/template/hook.tmpl
Ariel Mashraki 9cff230d34 entc/gen: temporary workaround for runtime.tmpl (#387)
* entc/gen: temporary workaround for runtime.tmpl

* ci: golangci version
2020-03-16 10:04:31 +02:00

68 lines
1.9 KiB
Cheetah

{{/*
Copyright 2019-present Facebook Inc. All rights reserved.
This source code is licensed under the Apache 2.0 license found
in the LICENSE file in the root directory of this source tree.
*/}}
{{ define "hook" }}
{{ with extend $ "Package" "hook" }}
{{ template "header" . }}
{{ end }}
import "{{ $.Config.Package }}"
{{ $pkg := base $.Config.Package }}
{{ range $n := $.Nodes }}
{{ $name := print $n.Name "Func" }}
{{ $type := printf "*%s.%s" $pkg $n.MutationName }}
// The {{ $name }} type is an adapter to allow the use of ordinary
// function as {{ $n.Name }} mutator.
type {{ $name }} func(context.Context, {{ $type }}) ({{ $pkg }}.Value, error)
// Mutate calls f(ctx, m).
func (f {{ $name }}) Mutate(ctx context.Context, m {{ $pkg }}.Mutation) ({{ $pkg }}.Value, error) {
mv, ok := m.({{ $type }})
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect {{ $type }}", m)
}
return f(ctx, mv)
}
{{ end }}
// On executes the given hook only of the given operation.
//
// hook.On(Log, {{ $pkg }}.Delete|{{ $pkg }}.Create)
//
func On(hk {{ $pkg }}.Hook, op {{ $pkg }}.Op) {{ $pkg }}.Hook {
return func(next {{ $pkg }}.Mutator) {{ $pkg }}.Mutator {
return {{ $pkg }}.MutateFunc(func(ctx context.Context, m {{ $pkg }}.Mutation) ({{ $pkg }}.Value, error) {
if m.Op().Is(op) {
return hk(next).Mutate(ctx, m)
}
return next.Mutate(ctx, m)
})
}
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []{{ $pkg }}.Hook {
// return []{{ $pkg }}.Hook{
// Reject({{ $pkg }}.Delete|{{ $pkg }}.Update),
// }
// }
//
func Reject(op {{ $pkg }}.Op) ent.Hook {
return func(next {{ $pkg }}.Mutator) {{ $pkg }}.Mutator {
return {{ $pkg }}.MutateFunc(func(ctx context.Context, m {{ $pkg }}.Mutation) ({{ $pkg }}.Value, error) {
if m.Op().Is(op) {
return nil, fmt.Errorf("%s operation is not allowed", m.Op())
}
return next.Mutate(ctx, m)
})
}
}
{{ end }}