Skip to content

Parameterized fragments #204

Open
Open
@rmosolgo

Description

@rmosolgo

A recent talk about Relay 2 suggested adding arguments to query fragments via directives.

I think first-class support for arguments in fragments would give a few benefits:

  • Smaller variable scope: instead of checking each usage of a fragment (which may be deeply nested) to determine what variables are available, a fragment would be its own scope. You could determine available variables by the fragment definition alone.
  • More flexible reuse: since a fragment wouldn't depend on its query's variables, fragments could be applied to queries whose variables had different names. They could also receive literal values when the query has no variables.

For example, a fragment might be defined with variables:

fragment avatarFields($thumbSize: Int = 40) on Image {
  thumbURL(size: $thumbSize)
  uploadedAt
}

The spread with different values:

{
  person(id: 1) {
    avatar {
      ... avatarFields(thumbSize: 80)
    }
  }
}
query findPerson($personId: Int!, $avatarSize: Int!) {
  person(id: $personId) {
    avatar {
      ... avatarFields(thumbSize: $avatarSize)
    }
  }
}

To be honest, I don't have a use case. But this seems like a really solid feature, and as a library maintainer, I'd rather add this language feature than implement some new directives! (Or, would those directives be "compiled out"?)

Technically, this could even be backwards compatible. Fragments could also use variables from their outer scope.

What do you think, would this be an improvement? Have I overlooked any downsides or complexities?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions