<commit_before>---
layout: guide
doc_stub: false
search: true
section: Queries
title: Lookahead
desc: Detecting child selections during field resolution
index: 11
---

GraphQL-Ruby 1.9+ includes {{ "GraphQL::Execution::Lookahead" | api_doc }} for checking whether child fields are selected. You can use this to optimize database access, for example, selecting only the _needed_ fields from the database.

## Getting a Lookahead

Add `extras: [:lookahead]` to your field configuration to recieve an injected lookahead:

```ruby
field :files, [Types::File], null: false, extras: [:lookahead]
```

Then, update your resolver method to accept a `lookahead:` argument:

```ruby
def files(lookahead:)
  # ...
end
```

That argument will be injected by the GraphQL runtime.

## Using a lookahead

Inside your field resolver, you can use the lookahead to check for child fields. For example, you can check for a __specific selection__:

```ruby
def files(lookahead:)
  if lookahead.selects?(:full_path)
    # This is a query like `files { fullPath ... }`
  else
    # This query doesn't have `fullPath`
  end
end
```<commit_msg>Update lookahead.md<commit_after>---
layout: guide
doc_stub: false
search: true
section: Queries
title: Lookahead
desc: Detecting child selections during field resolution
index: 11
---

GraphQL-Ruby 1.9+ includes {{ "GraphQL::Execution::Lookahead" | api_doc }} for checking whether child fields are selected. You can use this to optimize database access, for example, selecting only the _needed_ fields from the database.

## Getting a Lookahead

Add `extras: [:lookahead]` to your field configuration to receive an injected lookahead:

```ruby
field :files, [Types::File], null: false, extras: [:lookahead]
```

Then, update your resolver method to accept a `lookahead:` argument:

```ruby
def files(lookahead:)
  # ...
end
```

That argument will be injected by the GraphQL runtime.

## Using a lookahead

Inside your field resolver, you can use the lookahead to check for child fields. For example, you can check for a __specific selection__:

```ruby
def files(lookahead:)
  if lookahead.selects?(:full_path)
    # This is a query like `files { fullPath ... }`
  else
    # This query doesn't have `fullPath`
  end
end
```
{'fraction_non_alphanumeric': 0.10106856634016029, 'fraction_numerical': 0.003561887800534283, 'mean_word_length': 4.520884520884521, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2615733', 'n_tokens_mistral': 713, 'n_tokens_neox': 641, 'n_words': 285}