Skip to content

Decouple ElemMatch from schema.Array struct #276

@mihailquantive

Description

@mihailquantive

I'm trying to create my custom FieldValidator implementation that I want to use for fields that are actually arrays, but I have some issues when I try to use the $elemMatch operator on fields of that type.

The problem is that Prepare method of ElemMatch tries to cast field's validator to *schema.Array but my field is not of that type so the method returns an error:

func (e *ElemMatch) Prepare(validator schema.Validator) error {
	f, err := getValidatorField(e.Field, validator)
	if err != nil {
		return err
	}

	arr, ok := f.Validator.(*schema.Array)
	if !ok {
		return fmt.Errorf("%s: is not an array", e.Field)
	}

	// FIXME: Should allow any type.
	obj, ok := arr.Values.Validator.(*schema.Object)
	if !ok {
		return fmt.Errorf("%s: array elements are not schema.Object", e.Field)
	}

	return prepareExpressions(e.Exps, obj.Schema)
}

Can we somehow decouple the implementation of this method from the schema.Array struct? I was thinking of adding an interface that will look something like this:

type ArrayValidator interface { GetElementValidator() (Validator, error) }

... and cast the validator to that interface instead and then call the GetElementValidator()
What do you thing about that? If you like it I can open a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions