Allow infrastructural input validation
- Ngôn ngữ chính
- Go
- Star
- 10.8k
- Fork
- 1.3k
- Merge trung bình
- 2 ngày 36 phút
- Pull request đã merge (30 ngày)
- 26
Mô tả
In our schema we have inputs that heavily used in queries/mutations and may have a very well defined validation.
Example:
```graphql
scalar IpAddress
input IpAddressRangeInput {
from: IpAddress!
to: IpAddress!
}
```
It is obvious that `from` address must be less then or equal to `to` address.
Today i don't see a way in `gqlgen` to introduce such a validation to happen across ALL resolvers where this input is used.
For example we do have such ability for scalars https://gqlgen.com/reference/scalars/
It doesn't matter how deeply nested scalar field is inside input we can achieve infrastructural validation for it through defining custom `Unmarshal` function and registering it via config.
Unfortunately we lack such ability for inputs. The only thing i come up with is writing the `aroundFields` middleware and recursively scanning the `Field.Args` map looking for instances of generated struct. This is hard, requires custom traversing logic, working with reflection and just not friendly.
Few possible suggestions for improvement here:
1. Maybe we need to have some `AroundArgs` middleware? Maybe something like?
```go
ArgMiddleware func(ctx context.Context, next Resolver) (res interface{}, err error)
```
2. Maybe introduce some interface and allow developers do add methods to generated struct so it will start implementing some interface, and in generated code check if arg instance implements some ValidatedArg interface and in case it does run the Validate func:
```go
//somewhere inside the framework we have this interface:
type ValidationError error
type ValidatedArg interface {
Validate() ValidationError
}
// now i can make generated model struct to implement this interface by adding code to package
//where models are generated to and i'd expect this function to be called by framework before resolver is reached
func (model_gen.IpAddressRangeInput)Validate()graphql.ValidationError{
//validation code here.
}
```
3. Maybe some way to set a validator via config (inside gqlgen.yml):
```yml
models:
IpAddressRangeInput:
validator: "company/graph/validators.IpAddressRangeValidator"
```
WDYT about all of this? Does it make sense conceptually? Am i missing something and there is the way to achieve that in todays framework capabilities without reflections and ugly code?
If you find one of the ideas good, and consider it as something that could be added, but you don't have time implementing this, please communicate it with me, i will try to create a PR.
Hướng dẫn đóng góp
Đánh giá
Issue này chưa được đánh giá.