Khan / genqlient

a truly type-safe Go GraphQL client
MIT License
1.07k stars 107 forks source link

`# @genqlient(for: "Input.nonOptionalField", omitempty: false)` not working #290

Closed Anas737 closed 4 months ago

Anas737 commented 1 year ago

Describe the bug Hey all 👋

We are having a use-case where we want to apply omitempty on all fields except a mandatory graphql field.

We've tried the below code both at the top of the query and at the top of the $input line: # @genqlient(omitempty: true) # @genqlient(for: "Input.nonOptionalField", omitempty: false)

But we got the error: omitempty may only be used on optional arguments

Shouldn't omitempty be considered for non optional graphql fields when set to false?

When using # @genqlient(omitempty: true) only, it works on all fields including non optional graphql fields and adds the json:"fieldname,omitempty" to them.

To Reproduce Schema:

input Input {
    requiredField: Type!
    optionalField: Type
}

Query:

# @genqlient(omitempty: true)
# @genqlient(for: "Input.requiredField", omitempty: false)
mutation Name(
  $input: Input!
) {
  name(input: $input) {
     ...
  }
}

Happens at code generation running: go run -mod=readonly github.com/Khan/genqlient@v0.5.0

Expected behavior When using the below code at the top of the query: # @genqlient(omitempty: true) # @genqlient(for: "Input.nonOptionalField", omitempty: false)

I would expect omitempty to be added to all fields except the Input.nonOptionalField one. I tested and it worked when using only optional fields.

genqlient version Tested on both 0.5.0 and 0.6.0

benjaminjkraft commented 1 year ago

Thanks for raising this. I agree this is a bug. We can probably just change the validation (here and a few similar places in the same file) to only reject omitempty: true, not omitempty: false on non-nullable fields. Or, more correct (although probably more work) would be to just change the behavior so a global omitempty only applies to non-nullable fields; I don't see how that behavior as-is could be useful (and in most cases it just doesn't matter -- only if you try to pass the Go zero value which I assume is where you are finding trouble).

Anas737 commented 1 year ago

Thank you for looking into it

mwajeeh commented 1 year ago

I want it to add omitempty to everything but # @genqlient(omitempty: true) is throwing omitempty may only be used on optional arguments. Here is my mutaion:

# @genqlient(omitempty: true)
mutation ProvisionOrPortModalProvisionNumberMutation($input: ProvisionNumberInput!) {
    provisionNumber(input: $input) {
        errorMessage
        success
    }
}
benjaminjkraft commented 1 year ago

@mwajeeh you want to do:

# @genqlient(omitempty: true)
mutation ProvisionOrPortModalProvisionNumberMutation(
    $input: ProvisionNumberInput!,
) {
    provisionNumber(input: $input) {
        errorMessage
        success
    }
}

(See #151.)