contrib icon indicating copy to clipboard operation
contrib copied to clipboard

feat(entgql): add input field directives

Open danicc097 opened this issue 11 months ago • 0 comments

based on an old #543 and #469 concept and adds a complete example.

Fixes ent/ent#3407

some tests had to be updated to accommodate the new table

example use case:

field.Enum("role").
	Values("USER", "ADMIN", "MODERATOR").
	Default("USER").
	Annotations(entgql.Directives(
		hasRoleDirective(user.RoleADMIN).OnCreateMutationField().OnUpdateMutationField().SkipOnTypeField(),
	)),

which makes the field queryable but not editable unless admin.

The workaround right now is a schema hook like so, which may be error prone with e.g. forgetting clear and append and also gets out of hand quickly even if we abstract this to nested maps of directives where we also may forget to add/delete/modify a key.

entgql.WithSchemaHook(func(_ *gen.Graph, s *ast.Schema) error {
			for _, typ := range []string{"CreateUserInput", "UpdateUserInput"} {
				for _, name := range []string{"role"} {
					f := s.Types[typ].Fields.ForName(name)
					if f == nil {
						return fmt.Errorf("missing query field %q", name)
					}
					d := schema.HasRoleDirective(user.RoleADMIN)
					f.Directives = append(f.Directives, &ast.Directive{
						Name:      d.Name,
						Arguments: d.Arguments,
					})
				}
			}
			return nil
		}),

danicc097 avatar Jan 27 '25 16:01 danicc097